@lushly-dev/afd-server 2.5.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 (231) hide show
  1. package/README.md +65 -12
  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 +2 -2
  7. package/dist/app-call-registry.d.ts.map +1 -1
  8. package/dist/app-call-registry.js +12 -4
  9. package/dist/app-call-registry.js.map +1 -1
  10. package/dist/approval-admission.d.ts +47 -1
  11. package/dist/approval-admission.d.ts.map +1 -1
  12. package/dist/approval-admission.js +87 -0
  13. package/dist/approval-admission.js.map +1 -1
  14. package/dist/approval-crypto.d.ts +15 -1
  15. package/dist/approval-crypto.d.ts.map +1 -1
  16. package/dist/approval-crypto.js +43 -9
  17. package/dist/approval-crypto.js.map +1 -1
  18. package/dist/approval-process-state.d.ts +1 -0
  19. package/dist/approval-process-state.d.ts.map +1 -1
  20. package/dist/approval-process-state.js +1 -0
  21. package/dist/approval-process-state.js.map +1 -1
  22. package/dist/approval-relay.d.ts +23 -3
  23. package/dist/approval-relay.d.ts.map +1 -1
  24. package/dist/approval-relay.js +8 -11
  25. package/dist/approval-relay.js.map +1 -1
  26. package/dist/approval-up-front.d.ts.map +1 -1
  27. package/dist/approval-up-front.js +49 -5
  28. package/dist/approval-up-front.js.map +1 -1
  29. package/dist/approval.d.ts +48 -0
  30. package/dist/approval.d.ts.map +1 -1
  31. package/dist/approval.js +153 -26
  32. package/dist/approval.js.map +1 -1
  33. package/dist/approver.d.ts +2 -2
  34. package/dist/approver.d.ts.map +1 -1
  35. package/dist/approver.js +6 -6
  36. package/dist/approver.js.map +1 -1
  37. package/dist/auth-middleware-check.d.ts +23 -0
  38. package/dist/auth-middleware-check.d.ts.map +1 -0
  39. package/dist/auth-middleware-check.js +48 -0
  40. package/dist/auth-middleware-check.js.map +1 -0
  41. package/dist/bootstrap/afd-context.d.ts.map +1 -1
  42. package/dist/bootstrap/afd-context.js +27 -3
  43. package/dist/bootstrap/afd-context.js.map +1 -1
  44. package/dist/bootstrap/afd-help.d.ts +3 -1
  45. package/dist/bootstrap/afd-help.d.ts.map +1 -1
  46. package/dist/bootstrap/afd-help.js +2 -0
  47. package/dist/bootstrap/afd-help.js.map +1 -1
  48. package/dist/bootstrap/described-command.d.ts +2 -1
  49. package/dist/bootstrap/described-command.d.ts.map +1 -1
  50. package/dist/bootstrap/described-command.js.map +1 -1
  51. package/dist/command-allow.d.ts +4 -4
  52. package/dist/command-allow.d.ts.map +1 -1
  53. package/dist/command-allow.js +10 -15
  54. package/dist/command-allow.js.map +1 -1
  55. package/dist/command-routing.d.ts +56 -8
  56. package/dist/command-routing.d.ts.map +1 -1
  57. package/dist/command-routing.js +82 -16
  58. package/dist/command-routing.js.map +1 -1
  59. package/dist/command-timeout.d.ts.map +1 -1
  60. package/dist/command-timeout.js +8 -1
  61. package/dist/command-timeout.js.map +1 -1
  62. package/dist/confirmation-gate.d.ts +7 -7
  63. package/dist/confirmation-gate.d.ts.map +1 -1
  64. package/dist/confirmation-gate.js +26 -12
  65. package/dist/confirmation-gate.js.map +1 -1
  66. package/dist/confirmations.d.ts +28 -3
  67. package/dist/confirmations.d.ts.map +1 -1
  68. package/dist/confirmations.js +6 -7
  69. package/dist/confirmations.js.map +1 -1
  70. package/dist/context-fields.d.ts +16 -1
  71. package/dist/context-fields.d.ts.map +1 -1
  72. package/dist/context-fields.js +21 -4
  73. package/dist/context-fields.js.map +1 -1
  74. package/dist/context-scope.d.ts +3 -3
  75. package/dist/context-scope.d.ts.map +1 -1
  76. package/dist/context-scope.js +7 -8
  77. package/dist/context-scope.js.map +1 -1
  78. package/dist/define-core.d.ts +39 -3
  79. package/dist/define-core.d.ts.map +1 -1
  80. package/dist/define-core.js +20 -4
  81. package/dist/define-core.js.map +1 -1
  82. package/dist/define.d.ts +2 -2
  83. package/dist/define.d.ts.map +1 -1
  84. package/dist/define.js.map +1 -1
  85. package/dist/direct-registry.d.ts +28 -6
  86. package/dist/direct-registry.d.ts.map +1 -1
  87. package/dist/direct-registry.js +23 -2
  88. package/dist/direct-registry.js.map +1 -1
  89. package/dist/direct-tool-surface.d.ts.map +1 -1
  90. package/dist/direct-tool-surface.js +15 -3
  91. package/dist/direct-tool-surface.js.map +1 -1
  92. package/dist/direct.d.ts +4 -2
  93. package/dist/direct.d.ts.map +1 -1
  94. package/dist/direct.js +2 -0
  95. package/dist/direct.js.map +1 -1
  96. package/dist/execution.d.ts +35 -6
  97. package/dist/execution.d.ts.map +1 -1
  98. package/dist/execution.js +108 -15
  99. package/dist/execution.js.map +1 -1
  100. package/dist/host-state.d.ts +81 -0
  101. package/dist/host-state.d.ts.map +1 -0
  102. package/dist/host-state.js +62 -0
  103. package/dist/host-state.js.map +1 -0
  104. package/dist/http-handler.d.ts +31 -12
  105. package/dist/http-handler.d.ts.map +1 -1
  106. package/dist/http-handler.js +129 -103
  107. package/dist/http-handler.js.map +1 -1
  108. package/dist/http-security.js +2 -2
  109. package/dist/http-security.js.map +1 -1
  110. package/dist/http-sessions.d.ts +10 -0
  111. package/dist/http-sessions.d.ts.map +1 -1
  112. package/dist/http-sessions.js +12 -2
  113. package/dist/http-sessions.js.map +1 -1
  114. package/dist/http-sse.d.ts +9 -0
  115. package/dist/http-sse.d.ts.map +1 -1
  116. package/dist/http-sse.js +12 -3
  117. package/dist/http-sse.js.map +1 -1
  118. package/dist/human-relay.d.ts +195 -0
  119. package/dist/human-relay.d.ts.map +1 -0
  120. package/dist/human-relay.js +670 -0
  121. package/dist/human-relay.js.map +1 -0
  122. package/dist/idempotency-step.d.ts +231 -0
  123. package/dist/idempotency-step.d.ts.map +1 -0
  124. package/dist/idempotency-step.js +389 -0
  125. package/dist/idempotency-step.js.map +1 -0
  126. package/dist/idempotency-store.d.ts +107 -0
  127. package/dist/idempotency-store.d.ts.map +1 -0
  128. package/dist/idempotency-store.js +100 -0
  129. package/dist/idempotency-store.js.map +1 -0
  130. package/dist/index.d.ts +8 -5
  131. package/dist/index.d.ts.map +1 -1
  132. package/dist/index.js +7 -3
  133. package/dist/index.js.map +1 -1
  134. package/dist/instance-state.d.ts +7 -0
  135. package/dist/instance-state.d.ts.map +1 -1
  136. package/dist/instance-state.js +5 -2
  137. package/dist/instance-state.js.map +1 -1
  138. package/dist/journal-off-tape.d.ts +52 -0
  139. package/dist/journal-off-tape.d.ts.map +1 -0
  140. package/dist/journal-off-tape.js +150 -0
  141. package/dist/journal-off-tape.js.map +1 -0
  142. package/dist/journal-replay.d.ts.map +1 -1
  143. package/dist/journal-replay.js +7 -0
  144. package/dist/journal-replay.js.map +1 -1
  145. package/dist/journal-view.d.ts +50 -0
  146. package/dist/journal-view.d.ts.map +1 -0
  147. package/dist/journal-view.js +214 -0
  148. package/dist/journal-view.js.map +1 -0
  149. package/dist/journal.d.ts +24 -5
  150. package/dist/journal.d.ts.map +1 -1
  151. package/dist/journal.js +91 -40
  152. package/dist/journal.js.map +1 -1
  153. package/dist/lazy-tools.d.ts +13 -3
  154. package/dist/lazy-tools.d.ts.map +1 -1
  155. package/dist/lazy-tools.js +9 -2
  156. package/dist/lazy-tools.js.map +1 -1
  157. package/dist/mcp-auth-view.d.ts +2 -2
  158. package/dist/mcp-auth-view.d.ts.map +1 -1
  159. package/dist/mcp-auth-view.js +35 -22
  160. package/dist/mcp-auth-view.js.map +1 -1
  161. package/dist/mcp-auth.d.ts +17 -2
  162. package/dist/mcp-auth.d.ts.map +1 -1
  163. package/dist/mcp-auth.js +45 -13
  164. package/dist/mcp-auth.js.map +1 -1
  165. package/dist/mcp-modern.d.ts +70 -7
  166. package/dist/mcp-modern.d.ts.map +1 -1
  167. package/dist/mcp-modern.js +216 -110
  168. package/dist/mcp-modern.js.map +1 -1
  169. package/dist/meta-argument.d.ts +2 -1
  170. package/dist/meta-argument.d.ts.map +1 -1
  171. package/dist/meta-argument.js +13 -2
  172. package/dist/meta-argument.js.map +1 -1
  173. package/dist/meta-tools.js +2 -2
  174. package/dist/meta-tools.js.map +1 -1
  175. package/dist/middleware.d.ts +16 -1
  176. package/dist/middleware.d.ts.map +1 -1
  177. package/dist/middleware.js +42 -5
  178. package/dist/middleware.js.map +1 -1
  179. package/dist/output-budget.d.ts.map +1 -1
  180. package/dist/output-budget.js +2 -0
  181. package/dist/output-budget.js.map +1 -1
  182. package/dist/principal-binding.js +1 -1
  183. package/dist/principal-binding.js.map +1 -1
  184. package/dist/relay-evidence.d.ts +74 -0
  185. package/dist/relay-evidence.d.ts.map +1 -0
  186. package/dist/relay-evidence.js +143 -0
  187. package/dist/relay-evidence.js.map +1 -0
  188. package/dist/schema.d.ts +4 -3
  189. package/dist/schema.d.ts.map +1 -1
  190. package/dist/schema.js +3 -3
  191. package/dist/schema.js.map +1 -1
  192. package/dist/scope-view.d.ts +11 -5
  193. package/dist/scope-view.d.ts.map +1 -1
  194. package/dist/scope-view.js +9 -8
  195. package/dist/scope-view.js.map +1 -1
  196. package/dist/server-types.d.ts +33 -10
  197. package/dist/server-types.d.ts.map +1 -1
  198. package/dist/server-types.js.map +1 -1
  199. package/dist/server.d.ts +26 -0
  200. package/dist/server.d.ts.map +1 -1
  201. package/dist/server.js +278 -78
  202. package/dist/server.js.map +1 -1
  203. package/dist/task-dispatch.d.ts +6 -5
  204. package/dist/task-dispatch.d.ts.map +1 -1
  205. package/dist/task-dispatch.js +11 -12
  206. package/dist/task-dispatch.js.map +1 -1
  207. package/dist/tasks-runtime.d.ts +6 -4
  208. package/dist/tasks-runtime.d.ts.map +1 -1
  209. package/dist/tasks-runtime.js +97 -24
  210. package/dist/tasks-runtime.js.map +1 -1
  211. package/dist/tasks.d.ts +34 -7
  212. package/dist/tasks.d.ts.map +1 -1
  213. package/dist/tasks.js +42 -10
  214. package/dist/tasks.js.map +1 -1
  215. package/dist/tool-router.d.ts +64 -3
  216. package/dist/tool-router.d.ts.map +1 -1
  217. package/dist/tool-router.js +215 -69
  218. package/dist/tool-router.js.map +1 -1
  219. package/dist/tools.d.ts +32 -0
  220. package/dist/tools.d.ts.map +1 -1
  221. package/dist/tools.js +154 -40
  222. package/dist/tools.js.map +1 -1
  223. package/dist/up-front-steps.d.ts +8 -0
  224. package/dist/up-front-steps.d.ts.map +1 -1
  225. package/dist/up-front-steps.js +50 -1
  226. package/dist/up-front-steps.js.map +1 -1
  227. package/dist/validation.d.ts +14 -0
  228. package/dist/validation.d.ts.map +1 -1
  229. package/dist/validation.js +62 -17
  230. package/dist/validation.js.map +1 -1
  231. package/package.json +12 -8
package/README.md CHANGED
@@ -5,11 +5,13 @@ Server-side utilities for building AFD-compliant MCP servers with Zod validation
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- npm install @lushly-dev/afd-server
8
+ npm install @lushly-dev/afd-server zod
9
9
  # or
10
- pnpm add @lushly-dev/afd-server
10
+ pnpm add @lushly-dev/afd-server zod
11
11
  ```
12
12
 
13
+ `zod` (`^4.6.6`) is a peer dependency: your commands' schemas and the server share your application's copy.
14
+
13
15
  ## Features
14
16
 
15
17
  - **Zod-based Command Definition** - Define commands with Zod schemas for type-safe validation
@@ -259,7 +261,12 @@ imports from `/direct`. It exports everything `/define` does, plus:
259
261
  per call;
260
262
  - `createDirectToolSurface`, the MCP tool surface for that registry (see
261
263
  below);
262
- - `createApprovalMiddleware`, on WebCrypto (see [Approvals](#approvals));
264
+ - `createApprovalMiddleware`, on WebCrypto (see [Approvals](#approvals)). A
265
+ browser exposes WebCrypto only on a secure origin (HTTPS or `localhost`): over
266
+ plain HTTP from a network address, such as a phone opening
267
+ `http://192.168.x.x:5173/`, the app starts but every gated call returns
268
+ `APPROVAL_UNAVAILABLE` with `details.reason: "no-webcrypto"`. To test from
269
+ another device, serve HTTPS with a local certificate or use a tunnel;
263
270
  - `createJournalMiddleware`, `JOURNAL_RESULT_UNSERIALIZABLE`, `replayJournal` and `MemoryJournalSink`;
264
271
  - the middleware with no Node.js builtin in its module graph:
265
272
  `composeMiddleware`, `defaultMiddleware`, `createLoggingMiddleware`,
@@ -586,6 +593,10 @@ neither admitted credentials nor a valid bearer token still gets M5's 401.
586
593
 
587
594
  A server that also runs afd-auth's middleware passes `isVerifiedCredentials` to
588
595
  `createAuthMiddleware`, as [above](#verified-credentials-lushly-devafd-servercredentials).
596
+ A server with `auth` throws when it is built with afd-auth's middleware lacking it, in
597
+ `middleware` directly or inside `composeMiddleware`, rather than serve every token's call
598
+ as the adapter's session user. A middleware wrapped in a function of the host's own is not
599
+ seen, so it passes the option there too.
589
600
 
590
601
  ### Basic Command
591
602
 
@@ -709,7 +720,7 @@ Commands without `contexts` are universal (always visible). See "Context Managem
709
720
  ### Command that asks for confirmation
710
721
 
711
722
  A command with `confirmPrompt` can be gated on the server's MCP and HTTP surfaces with the
712
- `confirmations` option ([`spec/command-metadata.md`](../../spec/command-metadata.md#confirmations)):
723
+ `confirmations` option ([`spec/confirmations.md`](../../spec/confirmations.md)):
713
724
 
714
725
  ```typescript
715
726
  const clearTodos = defineCommand({
@@ -787,7 +798,7 @@ Two things are kept per process unless you share them:
787
798
  | What | Default | Used when | Share it with |
788
799
  |------|---------|-----------|---------------|
789
800
  | The key that signs elicitation `requestState` | A random key per server or handler, so even two handlers in one process do not share it | `confirmations` is not `'off'`, or an approval middleware has `relay: 'mcp-elicitation'` | `confirmationKey` on every instance (32 bytes or more) |
790
- | Spent single-use approval tokens | In memory, per `createApprovalMiddleware` | An approval middleware with the default `replay: 'single-use'` | `nonceStore` on every instance's approval middleware |
801
+ | Spent single-use approval tokens and relay decisions | In memory, per `createApprovalMiddleware` | An approval middleware with `replay: 'single-use'`, or any approval middleware on a server with `humanRelay` | `nonceStore` on every instance's approval middleware |
791
802
 
792
803
  Behind one process the defaults are enough. Behind several (a load balancer, or several engines answering the same callers), a `requestState` signed by one process is unanswered on another, so the person is asked again, and a single-use token works once on each process. Say which you run with `instances`:
793
804
 
@@ -897,7 +908,25 @@ const server = createMcpServer({
897
908
 
898
909
  ### Retries
899
910
 
900
- `createRetryMiddleware` reruns a command whose failure code passes `shouldRetry` (default: `TRANSIENT_ERROR` and `TIMEOUT`), up to `maxRetries` times (default: 3). The backoff is exponential and capped: retry `n` backs off `min(maxDelay, retryDelay * 2 ** (n - 1))`, with `retryDelay` defaulting to 100 ms and `maxDelay` to 5000 ms. With `jitter` (the default) each wait is a random time between half and all of that backoff; `jitter: false` waits exactly the backoff. When `context.signal` aborts, for example because the client disconnected or a batch deadline passed, the wait ends and the last failure is returned without further retries. Retry only commands that are safe to repeat.
911
+ `createRetryMiddleware` reruns a command whose failure code passes `shouldRetry` (default: `TRANSIENT_ERROR` and `TIMEOUT`), up to `maxRetries` times (default: 3). The backoff is exponential and capped: retry `n` backs off `min(maxDelay, retryDelay * 2 ** (n - 1))`, with `retryDelay` defaulting to 100 ms and `maxDelay` to 5000 ms. With `jitter` (the default) each wait is a random time between half and all of that backoff; `jitter: false` waits exactly the backoff. When `context.signal` aborts, for example because the client disconnected or a batch deadline passed, the wait ends and the last failure is returned without further retries.
912
+
913
+ What it repeats follows the command's declaration ([`spec/idempotency.md`](../../spec/idempotency.md#retrying), R1): a command declaring `idempotency: 'natural'` is retried; one declaring `idempotency: 'keyed'` only when the call carries an idempotency key; any other unless it declares `mutation: true`. A handler that returned `TIMEOUT` after a downstream write may already have applied it, and a retry of an undeclared mutation would apply it again. The middleware reads the declaration from the command the engine runs, not from its name; called directly, outside the engine, it counts every call as a mutation that declares nothing. Pass `retryMutations: true` only when every command it wraps is safe to repeat.
914
+
915
+ ### Idempotency keys
916
+
917
+ A caller that does not know whether its change was applied sends the same call again with the same key ([`spec/idempotency.md`](../../spec/idempotency.md)): in `_meta["dev.afd/idempotencyKey"]` over MCP, in a meta-tool's `meta` argument, or as `context.idempotencyKey` in process. The engine validates the key and puts it on the handler's context, so a handler that writes to a transactional store can commit the key with its write and answer a repeat itself. A server given the `idempotency` option does that for handlers that cannot, for commands that declare `idempotency: 'keyed'`:
918
+
919
+ ```typescript
920
+ const server = createMcpServer({
921
+ name: 'orders',
922
+ version: '1.0.0',
923
+ commands: [placeOrder], // declares mutation: true, idempotency: 'keyed'
924
+ // The default store is in memory, for this process only; several processes share one.
925
+ idempotency: { ttlMs: 86_400_000, leaseMs: 60_000 },
926
+ });
927
+ ```
928
+
929
+ A repeat with the same key and input gets the first result with `metadata.idempotentReplay: true`; another input gets `IDEMPOTENCY_KEY_REUSED`, a repeat while the first still runs `IDEMPOTENCY_IN_PROGRESS`, and a repeat of a call whose handler returned `TIMEOUT` or threw `OUTCOME_UNKNOWN`, since nobody can say whether it was applied. A direct registry takes a step built with `createIdempotencyStep(options, { clock })`.
901
930
 
902
931
  ```typescript
903
932
  import { createRetryMiddleware } from '@lushly-dev/afd-server';
@@ -1003,9 +1032,28 @@ An `afd-batch` or `afd-pipe` from a client that can elicit is approved up front,
1003
1032
 
1004
1033
  Only the command the tool call routes to can use the relay, once: a command that a handler runs cannot elicit. An accepted approval that has expired or was already used is asked again, and the question says so. `onApprovalRequired` is not called on the relay path, since no token exists.
1005
1034
 
1035
+ #### Recording an approval beside the call
1036
+
1037
+ A host that keeps its own record of what ran (an intent written before the handler, an audit trail stricter than the journal) needs two things AFD gives it ([`spec/dispatch.md`](../../spec/dispatch.md#the-dispatch-id), [the approval summary](../../spec/approvals.md#the-approval-summary)):
1038
+
1039
+ - **`context.dispatchId`**, an id the engine makes for each call: 128 random bits as 22 characters of base64url, never taken from the caller. Each batch item, pipeline step and command a handler runs gets its own, whatever trace id they share; a retry inside the chain keeps it. Middleware and the handler read it; a value a caller puts there is replaced, and a middleware that changes it does not change what later links read. It is not enumerable, so it is in no result, journal entry or context digest, and spread copies leave it out.
1040
+ - **`onApprovalAccepted(summary, dispatchId)`**, called when the approval step admits a held call, before the handler, and waited for. The summary says how the call was admitted (`via`: `token`, `elicitation`, `relay` or `direct`), the command, an `inputDigest` and an `approvalId`, with `issuedAt` and `expiresAt` when the evidence carries them. It holds no token or nonce. A hook that throws or rejects fails the call with `COMMAND_EXECUTION_ERROR` before the handler runs, and the evidence stays spent, so a host that must record the approval first can rely on it.
1041
+
1042
+ ```typescript
1043
+ createApprovalMiddleware({
1044
+ secret,
1045
+ onApprovalRequired: ({ approvalId, approvalToken }) => notifyApprover(approvalId, approvalToken),
1046
+ onApprovalAccepted: async (summary, dispatchId) => {
1047
+ await audit.write({ dispatchId, approval: summary.approvalId, via: summary.via });
1048
+ },
1049
+ });
1050
+ ```
1051
+
1052
+ `approvalId` is the join: `onApprovalRequired`'s request and DirectClient's `onApprovalNeeded` request carry the id the call's summary will have, so the surface that asks the person can keep it beside their answer. It names the approval, not the call: under `replay: 'within-ttl'` every call one token admits has the same `approvalId` and a different `dispatchId`. `inputDigest` is an unkeyed digest of the input, so store it only where you would store the input itself. Over the MCP relay no host code is asked, so only `onApprovalAccepted` sees the id.
1053
+
1006
1054
  #### An approver client
1007
1055
 
1008
- A trusted MCP client that shows a person the held action itself, such as an application shell that mounts this server, can carry the person's decision back (`spec/command-metadata.md`, "Approval evidence from an approver client"). Name it with `approver`, a predicate over the call's context after `createContext`:
1056
+ A trusted MCP client that shows a person the held action itself, such as an application shell that mounts this server, can carry the person's decision back (`spec/approvals.md`, "Approval evidence from an approver client"). Name it with `approver`, a predicate over the call's context after `createContext`:
1009
1057
 
1010
1058
  ```typescript
1011
1059
  createMcpServer({
@@ -1019,14 +1067,14 @@ createMcpServer({
1019
1067
  ```
1020
1068
 
1021
1069
  - **An approver gets the token:** its `APPROVAL_REQUIRED` results carry `details.approvalToken` whatever `includeToken` says, and the relay never answers it with a form.
1022
- - **It retries one command on MCP 2026-07-28** with the token in `_meta["dev.afd/approval"]` (`AFD_APPROVAL_META_KEY`) and the same input. On `afd-batch`, `afd-pipe` or a 2025-era request the key fails the call with `APPROVAL_REQUIRED` before anything runs.
1070
+ - **It retries one command on MCP 2026-07-28** with the token in `_meta["dev.afd/approval"]` (`AFD_APPROVAL_META_KEY`) and the same input. On `afd-batch`, `afd-pipe`, a 2025-era request or the HTTP `/rpc`, `/batch` and `/stream` routes the key fails the call with `APPROVAL_REQUIRED` before anything runs.
1023
1071
  - **Its tokens bind its principal binding** (the actor and the credentials' issuer, subject and client), so another client, even of the same person, gets `credentials-mismatch`.
1024
1072
  - **Anyone else's key is ignored,** and the key in tool arguments (or the HTTP routes' input) is refused with `VALIDATION_ERROR`, from every caller.
1025
1073
  - **The approver promises** never to give the token to an agent or a model, and to present it only on a retry a person approved after seeing the action, shown by `approvalDisplay` from `@lushly-dev/afd-core`, which refuses input too large, too deep or hiding characters.
1026
1074
 
1027
1075
  The relay trusts the MCP client application to put the question to a person. The server cannot tell a human's click from client code that accepts on its own, so the relay is off by default. Leave it off where the agent's own code is the MCP client, for example an `McpClient` whose `onElicitation` answers automatically. The relay's `requestState` is signed with the server's `confirmationKey`, a random key per process when it is not set, and its nonces are spent in the middleware's `nonceStore`, in memory per process by default: servers with several instances must share both and set `instances: 'multiple'` ([Several instances](#several-instances)).
1028
1076
 
1029
- `spec/command-metadata.md` ("Approvals") is the cross-language contract.
1077
+ `spec/approvals.md` is the cross-language contract.
1030
1078
 
1031
1079
  ### Declared Context Fields
1032
1080
 
@@ -1047,7 +1095,7 @@ await server.execute('project-summary', {}, { scope: { project: 'p-1' } });
1047
1095
  ```
1048
1096
 
1049
1097
  - The value is validated before middleware runs. An invalid value, or a missing `required: true` one, fails the call with `VALIDATION_ERROR`, whose `details` name the `field` and its `meta` key. `null` is no value. AFD's own `afd-*` commands do not enforce `required`, so a client can discover the fields first.
1050
- - Names AFD already uses (`actor`, `approval`, `auth`, `clock`, `credentials`, `interface`, `random`, `session`, `signal`, `source`, `timeout`, `traceId`) are refused, as is a `meta` key without a reverse-DNS prefix or with `dev.afd/` or an MCP-reserved prefix.
1098
+ - Names AFD already uses (`actor`, `approval`, `auth`, `clock`, `credentials`, `dispatchId`, `interface`, `random`, `session`, `signal`, `source`, `timeout`, `traceId`) are refused, as is a `meta` key without a reverse-DNS prefix or with `dev.afd/` or an MCP-reserved prefix.
1051
1099
  - A field is a claim made by the caller: use it to narrow what a handler does (pick a project), never to grant access. Check the caller's access to the claimed scope.
1052
1100
  - `journal: true` keeps the value in the journal (below). Only declare it for a field that never holds a secret.
1053
1101
  - Over MCP the value comes from `tools/call`'s `params._meta[meta]`, on both eras and over stdio and HTTP; undeclared `_meta` keys are dropped, and a value `createContext` sets for the same name wins. On AFD's HTTP lanes, `/message` reads `params._meta`, `/rpc` reads `params._meta` and `/stream` the `_meta` member of its input (both leave it out of the command input), and `/batch` reads the body's `_meta`.
@@ -1056,7 +1104,7 @@ await server.execute('project-summary', {}, { scope: { project: 'p-1' } });
1056
1104
 
1057
1105
  ### Command Journal and Replay
1058
1106
 
1059
- `createJournalMiddleware(sink)` records each accepted call (validation and lookup rejections never reach middleware) as a `JournalEntry`: command, validated input, actor, trace ID, a context digest, the result and the duration. Context values outside the allowlist (actor, interface, trace ID) are never stored, so auth sessions and tokens stay out of the journal. Each entry also holds a tape of the values the handler read from `context.clock` and `context.random`. Failures are recorded only with `recordFailures: true`. When a result cannot be copied as JSON (a throwing getter, circular reference or `bigint`), the error goes to `onError`, the live return value is unchanged, and the entry records a `JOURNAL_RESULT_UNSERIALIZABLE` failure instead of dropping the call. A [declared context field](#declared-context-fields) marked `journal: true` is kept in the entry's `context`, or named in `contextOmitted` when its canonical JSON exceeds 4096 bytes, and replay restores it. Commands named `auth-*` are skipped by default; `filter` and `redact` keep other secret inputs or results out (drop `tape` as well when a secret comes from `context.random`). Put it last in the middleware list.
1107
+ `createJournalMiddleware(sink)` records each accepted call (validation and lookup rejections never reach middleware) as a `JournalEntry`: command, validated input, actor, trace ID, a context digest, the result and the duration. Context values outside the allowlist (actor, interface, trace ID) are never stored, so auth sessions and tokens stay out of the journal. Each entry also holds a tape of the values the handler read from `context.clock` and `context.random`. Those reads are each call's own: where the runtime has `AsyncLocalStorage` (Node 22.3 and later), the journal gives the call, the calls nested in it and the work they start their own view of the two sources, so a concurrent call on the same context object reads the context's own and never lands on this call's tape (#2890); in a browser it sets them on the context for the length of the call, so give each dispatch its own context there, as every engine here does. Failures are recorded only with `recordFailures: true`. When a result cannot be copied as JSON (a throwing getter, circular reference or `bigint`), the error goes to `onError`, the live return value is unchanged, and the entry records a `JOURNAL_RESULT_UNSERIALIZABLE` failure instead of dropping the call. A [declared context field](#declared-context-fields) marked `journal: true` is kept in the entry's `context`, or named in `contextOmitted` when its canonical JSON exceeds 4096 bytes, and replay restores it. Commands named `auth-*` are skipped by default; `filter` and `redact` keep other secret inputs or results out (drop `tape` as well when a secret comes from `context.random`). Put it last in the middleware list.
1060
1108
 
1061
1109
  `replayJournal(registry, entries)` re-runs the entries in order against a fresh server or registry, feeds each call its recorded clock and random values, and reports every entry as `same`, `different` (with a structural diff) or `error`. For an entry recorded with `JOURNAL_RESULT_UNSERIALIZABLE`, replay still runs the command and adds a note that the original result was not captured: an unserializable replayed result reports `error`, a serializable one reports `different`, and a recorded-answer target returning the entry verbatim reports `same` with the note. Replay against a server with the same middleware: the journal middleware in it lines the tape up with the handler and records nothing during replay. It reports divergence; it does not make other nondeterminism go away. A journal entry does not show that a call was approved: with `recordFailures: true` the journal also keeps calls that never ran, such as an `APPROVAL_REQUIRED` hold, and `replayJournal` executes every entry it is given before comparing, failed ones included. So replay gated commands against a target with the approval middleware, which holds them again, or pass only the entries whose recorded result succeeded (`entries.filter((entry) => entry.result.success)`) to a target that serves those commands with `approval: 'not-required'`. A target without either refuses them with `APPROVAL_UNAVAILABLE`. The format is specified in [`spec/journal.md`](../../spec/journal.md).
1062
1110
 
@@ -1133,7 +1181,10 @@ on, `mcp` and `cli` off), so `expose: { mcp: true }` stays available to agents.
1133
1181
  Set `expose: { agent: false }` to keep a command away from in-app agents.
1134
1182
  Commands that are registered but not exposed are left out of
1135
1183
  `listCommands()`/`hasCommand()`, and `execute()` returns `COMMAND_NOT_EXPOSED`
1136
- for them. Duplicate command names throw.
1184
+ for them. Duplicate command names throw. `listCommands()` returns each exposed
1185
+ command's summary including `title`, `category`, `mutation`, `destructive`,
1186
+ `confirmPrompt`, `undoable`, `requires`, `tags`, `examples`, and `inputSchema`
1187
+ when declared.
1137
1188
 
1138
1189
  ## Validation Utilities
1139
1190
 
@@ -1192,6 +1243,7 @@ Create a command definition with Zod schema.
1192
1243
  | `expose` | ExposeOptions | No | Surfaces the command is exposed to; `{ mcp: true }` is required for MCP tools |
1193
1244
  | `examples` | `{ title, input }[]` | No | Example inputs, validated against `input` at define time |
1194
1245
  | `approval` | `'required'` \| `'not-required'` \| `(input, context) => …` | No | Whether a call needs human approval before the handler runs (default `'not-required'`); enforced by [`createApprovalMiddleware`](#approvals), and refused with `APPROVAL_UNAVAILABLE` when no approval middleware admits the call |
1246
+ | `confirmationMode` | `'host-verified'` | No | Requires a person's out-of-band confirmation through `createMcpServer({ humanRelay })`; never accepts `confirm`, form elicitation or form-mode approval relay, and cannot be combined with `task: 'optional' \| 'required'` |
1195
1247
  | `toolMeta` | `Record<string, unknown>` | No | Extra `_meta` entries on the command's tool, grouped action entry and `afd-detail`: prefixed keys with two or more labels, or `ui`; the server refuses others (see [Resources, Skills and Tool `_meta`](#resources-skills-and-tool-_meta)) |
1196
1248
  | `advertisedInputSchema` | JSON Schema object | No | The input schema shown on every surface in place of the one generated from `input`, which still validates |
1197
1249
 
@@ -1231,6 +1283,7 @@ Create an MCP server from commands.
1231
1283
  | `resources` | `ResourceProvider \| ResourceEntry[]` | No | MCP resources served on `/mcp` and stdio; declares the `resources` capability |
1232
1284
  | `skills` | `SkillCatalog` | No | Agent Skills served through `skills/list`, `skills/get` and as `skill://` resources; declares `io.modelcontextprotocol/skills` |
1233
1285
  | `confirmations` | `'off' \| 'enforce' \| 'require-human'` | No | Enforce `confirmPrompt` on the MCP and HTTP surfaces (default: `'off'`) |
1286
+ | `humanRelay` | `HumanRelay` | No | Host-owned out-of-band confirmation relay (`begin`, `resume`, optional `approvedContext` and `pendingList`) for commands with `confirmationMode: 'host-verified'` |
1234
1287
  | `confirmationKey` | `string \| Uint8Array` | No | Key (32 bytes or more) that signs elicitation `requestState` (default: a random key per process) |
1235
1288
  | `instances` | `'single' \| 'multiple'` | No | `'multiple'` refuses per-process defaults in use; left out, HTTP logs one warning when it relies on one ([Several instances](#several-instances)) |
1236
1289
  | `middleware` | array | No | Middleware functions |
@@ -0,0 +1,137 @@
1
+ /**
2
+ * @fileoverview One admission pipeline for every lane of the MCP server (#1743).
3
+ *
4
+ * Each lane (the MCP 2026-07-28 `/mcp` endpoint and stdio, the 2025-era `/message` lane, and the
5
+ * HTTP `/rpc`, `/batch` and `/stream` routes) only decodes its request into a {@link DecodedCall}
6
+ * and encodes the outcome. Admission runs the same named stages for all of them, in this order:
7
+ *
8
+ * 1. `evidence`: approval evidence in the arguments is refused, from any caller (rule 5 of
9
+ * "Approval evidence from an approver client", `spec/approvals.md`).
10
+ * 2. `meta`: a meta-tool's `meta` argument counts as `_meta` from here on.
11
+ * 3. `principal`: the call's context state, `createContext`'s values, the declared context fields
12
+ * and the output-budget ask (`createContext` wins over a declared field), and the actor and
13
+ * credentials the call starts with.
14
+ * 4. `approver`: whether the caller is an approver, and whether it may carry its evidence here
15
+ * (only on one command from an MCP 2026-07-28 client).
16
+ * 5. `bind`: the call's `CommandContext`: the values a handler sees, with the session, scope view,
17
+ * approver and the lane's channels in its host state (`host-state.ts`).
18
+ *
19
+ * Then the tool router (`tool-router.ts`) runs the rest, the same on every lane:
20
+ *
21
+ * 6. `scope`: MCP authorization (M6), a batch or pipeline as a whole;
22
+ * 7. `resolve`: the tool to its commands (one for `afd-call`, a grouped action or a command's own
23
+ * tool; several for `afd-batch` and `afd-pipe`; none for `afd-discover` and `afd-detail`);
24
+ * 8. `allow`, 9. `lookup` (D4: unexposed and hidden commands are unknown), 10. `context`
25
+ * (`COMMAND_NOT_IN_CONTEXT`), 11. `host-verified`, 12. `confirm`, 13. `task`;
26
+ * 14. `execute`: the engine (`spec/dispatch.md`, from input validation on).
27
+ *
28
+ * A stage that refuses ends the call with its error. A refusal of stages 1 to 5 is a `CommandResult`
29
+ * over MCP, whatever the tool (`spec/vectors/approver-client.json`), a `BatchResult` on `/batch`
30
+ * and an error chunk on `/stream`; the router shapes its own refusals as the tool's result. The
31
+ * HTTP routes decode as the meta-tools they stand for: `/rpc` and `/stream` as `afd-call`, and
32
+ * `/batch` as `afd-batch`, so one call gets the same answer on every lane.
33
+ *
34
+ * Unexpected errors (a throwing `createContext` or `approver` predicate, credentials that cannot
35
+ * be bound) are thrown to the lane, which answers them as an internal error.
36
+ */
37
+ import type { Actor, CommandContext, CommandError } from '@lushly-dev/afd-core';
38
+ import { type ApproverCall, type ApproverPredicate } from './approver.js';
39
+ import type { ContextState } from './bootstrap/afd-context.js';
40
+ import { type ContextField } from './context-fields.js';
41
+ import { type ScopeView } from './scope-view.js';
42
+ import type { RouteOutcome, RunAdmitted, ToolRouter } from './tool-router.js';
43
+ /** Which lane received a call: what it can carry differs, the stages do not. */
44
+ export type AdmissionLane =
45
+ /** MCP 2026-07-28: `POST /mcp` and a modern stdio connection. */
46
+ 'mcp'
47
+ /** A 2025-era MCP request: the `/message` lane, a legacy `/mcp` or stdio connection. */
48
+ | 'mcp-legacy'
49
+ /** The HTTP `/rpc`, `/batch` and `/stream` routes. */
50
+ | 'rest';
51
+ /** The stages admission runs before the router, by name. */
52
+ export declare const ADMISSION_STAGES: readonly ['evidence', 'meta', 'principal', 'approver', 'bind'];
53
+ /** Who a call runs as, as it starts. */
54
+ export interface CallPrincipal {
55
+ /** The actor the commands run with: `createContext`'s, or the server's default. */
56
+ readonly actor: Actor | undefined;
57
+ /** `createContext`'s (or the verified request's) credentials. */
58
+ readonly credentials: unknown;
59
+ /** The approver's call, when the caller is an approver. */
60
+ readonly approver: ApproverCall | undefined;
61
+ }
62
+ /** One call, as a lane decoded it. */
63
+ export interface DecodedCall {
64
+ readonly lane: AdmissionLane;
65
+ /** The tool called. `/rpc` and `/stream` decode as `afd-call`, `/batch` as `afd-batch`. */
66
+ readonly tool: string;
67
+ /** The tool's arguments, without `_meta`. */
68
+ readonly args: unknown;
69
+ /** The request's own `_meta`. */
70
+ readonly meta: unknown;
71
+ /**
72
+ * The caller's context state, given the call's `_meta` values (the `meta` stage's): a
73
+ * session's, a request's, `null` for a caller without one, or `undefined` for the server's own.
74
+ * May throw the lane's protocol error (an unknown context, an unknown session).
75
+ */
76
+ state(meta: unknown): ContextState | null | undefined;
77
+ /** `createContext`'s values for the request (none on stdio). */
78
+ values(): Promise<Record<string, unknown>> | Record<string, unknown>;
79
+ /** The request's scope view under MCP authorization (M6). */
80
+ readonly view?: ScopeView;
81
+ /** Aborts the call (the client went away). */
82
+ readonly signal?: AbortSignal;
83
+ /**
84
+ * How the lane tells callers apart, for the idempotency step (`spec/idempotency.md`, S3):
85
+ * `http` for an HTTP request, or the connection a stdio call arrived on. Absent: in process.
86
+ */
87
+ readonly transport?: {
88
+ readonly kind: 'http';
89
+ } | {
90
+ readonly kind: 'connection';
91
+ readonly connection: object;
92
+ };
93
+ /**
94
+ * Bind what this request can carry (confirmation and relay channels, the approval relay, task
95
+ * dispatch) to the call's context, once its principal is known.
96
+ */
97
+ channels?(context: CommandContext, principal: CallPrincipal): CommandContext;
98
+ }
99
+ /** What stages 1 to 5 decided. */
100
+ export type Admission = {
101
+ kind: 'refused';
102
+ stage: (typeof ADMISSION_STAGES)[number];
103
+ error: CommandError;
104
+ } | {
105
+ kind: 'admitted';
106
+ tool: string;
107
+ args: unknown;
108
+ context: CommandContext;
109
+ };
110
+ export interface AdmissionDeps {
111
+ /** Runs stages 6 to 14. */
112
+ router: ToolRouter;
113
+ /** Declared context fields, read from each call's `_meta`. */
114
+ contextFields?: readonly ContextField[];
115
+ /** Which callers are approvers (the server's `approver` option). */
116
+ approver?: ApproverPredicate;
117
+ /** The actor of a call whose context has none (the server's `actor` option). */
118
+ actor?: Actor;
119
+ /**
120
+ * Whether the server can tell apart the HTTP caller with `credentials` (S3): it has `auth` and
121
+ * the request carries credentials, or `createContext` is declared to identify every caller.
122
+ * Default: it cannot.
123
+ */
124
+ identifiesHttpCaller?: (credentials: unknown) => boolean;
125
+ }
126
+ export interface AdmissionPipeline {
127
+ /** Run stages 1 to 5. */
128
+ admit(call: DecodedCall): Promise<Admission>;
129
+ /**
130
+ * Admit `call` and route it; `run` replaces the engine for the one command a single-command
131
+ * call admits (the `/stream` lane streams it).
132
+ */
133
+ run(call: DecodedCall, run?: RunAdmitted): Promise<RouteOutcome>;
134
+ }
135
+ /** Create the admission pipeline every lane of one server shares. */
136
+ export declare function createAdmission(deps: AdmissionDeps): AdmissionPipeline;
137
+ //# sourceMappingURL=admission.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admission.d.ts","sourceRoot":"","sources":["../src/admission.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEhF,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,iBAAiB,EAItB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,KAAK,YAAY,EAAsB,MAAM,qBAAqB,CAAC;AAM5E,OAAO,EAAiB,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAChE,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9E,gFAAgF;AAChF,MAAM,MAAM,aAAa;AACxB,iEAAiE;AAC/D,KAAK;AACP,wFAAwF;GACtF,YAAY;AACd,sDAAsD;GACpD,MAAM,CAAC;AAEV,4DAA4D;AAC5D,eAAO,MAAM,gBAAgB,YAAI,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,CAAU,CAAC;AAE/F,wCAAwC;AACxC,MAAM,WAAW,aAAa;IAC7B,mFAAmF;IACnF,QAAQ,CAAC,KAAK,EAAE,KAA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AC,KAAK,EAAE,YAAY,CAAA;CAAE,GAClF;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,cAAc,CAAA;CAAE,CAAC;AAE9E,MAAM,WAAW,aAAa;IAC7B,2BAA2B;IAC3B,MAAM,EAAE,UAAU,CAAC;IACnB,8DAA8D;IAC9D,aAAa,CAAC,EAAE,SAAS,YAAY,EAAE,CAAC;IACxC,oEAAoE;IACpE,QAAQ,CAAC,EAAE,iBAAiB,CAAC;IAC7B,gFAAgF;IAChF,KAAK,CAAC,EAAE,KAAK,CAAC;IACd;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,CAAC,WAAW,EAAE,OAAO,KAAK,OAAO,CAAC;CACzD;AAED,MAAM,WAAW,iBAAiB;IACjC,yBAAyB;IACzB,KAAK,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;IAC7C;;;OAGG;IACH,GAAG,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;CACjE;AAkBD,qEAAqE;AACrE,wBAAgB,eAAe,CAAC,IAAI,EAAE,aAAa,GAAG,iBAAiB,CA4FtE"}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * @fileoverview One admission pipeline for every lane of the MCP server (#1743).
3
+ *
4
+ * Each lane (the MCP 2026-07-28 `/mcp` endpoint and stdio, the 2025-era `/message` lane, and the
5
+ * HTTP `/rpc`, `/batch` and `/stream` routes) only decodes its request into a {@link DecodedCall}
6
+ * and encodes the outcome. Admission runs the same named stages for all of them, in this order:
7
+ *
8
+ * 1. `evidence`: approval evidence in the arguments is refused, from any caller (rule 5 of
9
+ * "Approval evidence from an approver client", `spec/approvals.md`).
10
+ * 2. `meta`: a meta-tool's `meta` argument counts as `_meta` from here on.
11
+ * 3. `principal`: the call's context state, `createContext`'s values, the declared context fields
12
+ * and the output-budget ask (`createContext` wins over a declared field), and the actor and
13
+ * credentials the call starts with.
14
+ * 4. `approver`: whether the caller is an approver, and whether it may carry its evidence here
15
+ * (only on one command from an MCP 2026-07-28 client).
16
+ * 5. `bind`: the call's `CommandContext`: the values a handler sees, with the session, scope view,
17
+ * approver and the lane's channels in its host state (`host-state.ts`).
18
+ *
19
+ * Then the tool router (`tool-router.ts`) runs the rest, the same on every lane:
20
+ *
21
+ * 6. `scope`: MCP authorization (M6), a batch or pipeline as a whole;
22
+ * 7. `resolve`: the tool to its commands (one for `afd-call`, a grouped action or a command's own
23
+ * tool; several for `afd-batch` and `afd-pipe`; none for `afd-discover` and `afd-detail`);
24
+ * 8. `allow`, 9. `lookup` (D4: unexposed and hidden commands are unknown), 10. `context`
25
+ * (`COMMAND_NOT_IN_CONTEXT`), 11. `host-verified`, 12. `confirm`, 13. `task`;
26
+ * 14. `execute`: the engine (`spec/dispatch.md`, from input validation on).
27
+ *
28
+ * A stage that refuses ends the call with its error. A refusal of stages 1 to 5 is a `CommandResult`
29
+ * over MCP, whatever the tool (`spec/vectors/approver-client.json`), a `BatchResult` on `/batch`
30
+ * and an error chunk on `/stream`; the router shapes its own refusals as the tool's result. The
31
+ * HTTP routes decode as the meta-tools they stand for: `/rpc` and `/stream` as `afd-call`, and
32
+ * `/batch` as `afd-batch`, so one call gets the same answer on every lane.
33
+ *
34
+ * Unexpected errors (a throwing `createContext` or `approver` predicate, credentials that cannot
35
+ * be bound) are thrown to the lane, which answers them as an internal error.
36
+ */
37
+ import { AFD_IDEMPOTENCY_KEY_META_KEY } from '@lushly-dev/afd-core';
38
+ import { approvalKeyInInput, bindApprover, decideApprover, } from './approver.js';
39
+ import { contextFieldValues } from './context-fields.js';
40
+ import { bindContextState } from './context-scope.js';
41
+ import { withHostState } from './host-state.js';
42
+ import { liftMetaArgument, metaArgumentKeys } from './meta-argument.js';
43
+ import { withMetaOutputBudget } from './output-budget.js';
44
+ import { bindScopeView } from './scope-view.js';
45
+ /** The stages admission runs before the router, by name. */
46
+ export const ADMISSION_STAGES = ['evidence', 'meta', 'principal', 'approver', 'bind'];
47
+ function isRecord(value) {
48
+ return !!value && typeof value === 'object' && !Array.isArray(value);
49
+ }
50
+ /** `_meta["dev.afd/idempotencyKey"]` as `idempotencyKey`, or nothing for an absent or null key. */
51
+ function idempotencyKeyOf(meta) {
52
+ if (!isRecord(meta))
53
+ return {};
54
+ const key = meta[AFD_IDEMPOTENCY_KEY_META_KEY];
55
+ return key === undefined || key === null ? {} : { idempotencyKey: key };
56
+ }
57
+ /** A shallow copy of a plain object; anything else as it is. */
58
+ function shallowCopy(value) {
59
+ return isRecord(value) ? { ...value } : value;
60
+ }
61
+ /** Create the admission pipeline every lane of one server shares. */
62
+ export function createAdmission(deps) {
63
+ const metaKeys = metaArgumentKeys(deps.contextFields);
64
+ async function admit(call) {
65
+ // 1. evidence: approval evidence is never input, from any caller.
66
+ const keyed = approvalKeyInInput(call.args);
67
+ if (keyed)
68
+ return { kind: 'refused', stage: 'evidence', error: keyed };
69
+ // 2. meta: a meta-tool's `meta` argument counts as `_meta` from here on.
70
+ const lifted = liftMetaArgument(call.tool, call.args, call.meta, metaKeys);
71
+ if (!lifted.ok)
72
+ return { kind: 'refused', stage: 'meta', error: lifted.error };
73
+ // 3. principal. Declared fields from `_meta` first, so a value `createContext` sets wins.
74
+ // Neither `actor` nor `credentials` can be a declared field: only `createContext` sets them.
75
+ const state = call.state(lifted.meta);
76
+ const values = await call.values();
77
+ const callValues = withMetaOutputBudget({
78
+ ...contextFieldValues(deps.contextFields, lifted.meta),
79
+ // The idempotency key, as sent: the engine checks its form between the context check and
80
+ // validation (spec/idempotency.md, K2). A value `createContext` sets wins (K1).
81
+ ...idempotencyKeyOf(lifted.meta),
82
+ ...values,
83
+ }, lifted.meta, values);
84
+ // Copied, so that code changing them in place later cannot change what a channel binds.
85
+ const actor = shallowCopy(callValues.actor ?? deps.actor);
86
+ const credentials = shallowCopy(callValues.credentials);
87
+ // 4. approver: an approver's call carries its evidence in the request's own `_meta`.
88
+ const carrier = decideApprover({
89
+ approver: deps.approver,
90
+ context: { ...callValues, actor, interface: 'mcp' },
91
+ actor,
92
+ credentials,
93
+ meta: call.meta,
94
+ tool: call.tool,
95
+ modern: call.lane === 'mcp',
96
+ });
97
+ if (carrier.kind === 'refuse')
98
+ return { kind: 'refused', stage: 'approver', error: carrier.error };
99
+ // 5. bind: the values a handler sees, and the host state it cannot.
100
+ const values5 = {
101
+ ...callValues,
102
+ ...(call.signal && { signal: call.signal }),
103
+ interface: 'mcp',
104
+ };
105
+ let context = bindScopeView(state === undefined ? values5 : bindContextState(values5, state), call.view);
106
+ const caller = idempotencyCaller(call, credentials);
107
+ if (caller)
108
+ context = withHostState(context, { idempotencyCaller: caller });
109
+ if (carrier.approver)
110
+ context = bindApprover(context, carrier.approver);
111
+ if (call.channels) {
112
+ context = call.channels(context, { actor, credentials, approver: carrier.approver });
113
+ }
114
+ return { kind: 'admitted', tool: call.tool, args: lifted.args ?? {}, context };
115
+ }
116
+ /**
117
+ * Who the lane says the caller is (S3): an HTTP caller, identified or not; or, on a connection
118
+ * lane, the connection. Whether a connection's caller has an identity of its own is the step's
119
+ * to decide, after middleware, which may set the actor.
120
+ */
121
+ function idempotencyCaller(call, credentials) {
122
+ const transport = call.transport;
123
+ if (!transport)
124
+ return undefined;
125
+ if (transport.kind === 'http') {
126
+ return { kind: 'http', identified: deps.identifiesHttpCaller?.(credentials) === true };
127
+ }
128
+ return {
129
+ kind: 'connection',
130
+ connection: transport.connection,
131
+ ...(deps.actor !== undefined && { defaultActor: deps.actor }),
132
+ };
133
+ }
134
+ return {
135
+ admit,
136
+ async run(call, run) {
137
+ const admission = await admit(call);
138
+ if (admission.kind === 'refused')
139
+ return { kind: 'refused', error: admission.error };
140
+ return deps.router.route(admission.tool, admission.args, admission.context, run);
141
+ },
142
+ };
143
+ }
144
+ //# sourceMappingURL=admission.js.map
@@ -0,0 +1 @@
1
+ {"version":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,CAAC,IAAI,EAAE,SAAS,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;QAClF,CAAC;KACD,CAAC;AACH,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import { type CallGrant } from '@lushly-dev/afd-core/internal/app-calls';
2
2
  import { type DirectCommandRegistry, type DirectRegistryOptions } from './direct-registry.js';
3
- import type { ZodCommandDefinition } from './schema.js';
3
+ import type { AnyZodCommandDefinition } from './schema.js';
4
4
  /** Options for {@link createAppCallRegistry}: `createDirectRegistry`'s, less `interface` and `tools`. */
5
5
  export interface AppCallRegistryOptions extends Omit<DirectRegistryOptions, 'interface' | 'tools'> {
6
6
  /**
@@ -27,5 +27,5 @@ export interface AppCallRegistryOptions extends Omit<DirectRegistryOptions, 'int
27
27
  *
28
28
  * @throws TypeError without `callGrant`; otherwise as `createDirectRegistry`
29
29
  */
30
- export declare function createAppCallRegistry(commands: ZodCommandDefinition[], options: AppCallRegistryOptions): DirectCommandRegistry;
30
+ export declare function createAppCallRegistry(commands: AnyZodCommandDefinition[], options: AppCallRegistryOptions): DirectCommandRegistry;
31
31
  //# sourceMappingURL=app-call-registry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"app-call-registry.d.ts","sourceRoot":"","sources":["../src/app-call-registry.ts"],"names":[],"mappings":"AAOA,OAAO,EAEN,KAAK,SAAS,EAEd,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAGN,KAAK,qBAAqB,EAC1B,KAAK,qBAAqB,EAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAExD,yGAAyG;AACzG,MAAM,WAAW,sBAAuB,SAAQ,IAAI,CAAC,qBAAqB,EAAE,WAAW,GAAG,OAAO,CAAC;IACjG;;;;;OAKG;IACH,SAAS,EAAE,SAAS,CAAC;CACrB;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,qBAAqB,CACpC,QAAQ,EAAE,oBAAoB,EAAE,EAChC,OAAO,EAAE,sBAAsB,GAC7B,qBAAqB,CA+BvB"}
1
+ {"version":3,"file":"app-call-registry.d.ts","sourceRoot":"","sources":["../src/app-call-registry.ts"],"names":[],"mappings":"AAOA,OAAO,EAEN,KAAK,SAAS,EAEd,MAAM,yCAAyC,CAAC;AAMjD,OAAO,EAGN,KAAK,qBAAqB,EAC1B,KAAK,qBAAqB,EAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAE3D,yGAAyG;AACzG,MAAM,WAAW,sBAAuB,SAAQ,IAAI,CAAC,qBAAqB,EAAE,WAAW,GAAG,OAAO,CAAC;IACjG;;;;;OAKG;IACH,SAAS,EAAE,SAAS,CAAC;CACrB;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,qBAAqB,CACpC,QAAQ,EAAE,uBAAuB,EAAE,EACnC,OAAO,EAAE,sBAAsB,GAC7B,qBAAqB,CAsCvB"}
@@ -1,11 +1,12 @@
1
1
  /**
2
- * The in-process registry for app-to-app calls (`spec/command-metadata.md`, "App-to-app calls").
2
+ * The in-process registry for app-to-app calls (`spec/app-calls.md`).
3
3
  *
4
4
  * Its own module, so a host that never serves app calls bundles none of it: `createDirectRegistry`
5
5
  * only refuses the `apps` interface.
6
6
  */
7
7
  import { failure } from '@lushly-dev/afd-core';
8
8
  import { appCallGranted, callNotGranted, } from '@lushly-dev/afd-core/internal/app-calls';
9
+ import { createDispatchId, presetDispatchId, setDispatchId, } from '@lushly-dev/afd-core/internal/dispatch-id';
9
10
  import { APP_CALLS, createDirectRegistry, } from './direct-registry.js';
10
11
  /**
11
12
  * Create the registry a host runs an app's calls through, with the `apps` interface.
@@ -40,11 +41,18 @@ export function createAppCallRegistry(commands, options) {
40
41
  interface: registry.interface,
41
42
  contextFields: registry.contextFields,
42
43
  async execute(name, input, context = {}, callOptions) {
43
- // The grant check sees the interface the call runs with, as in the core registry.
44
- const appContext = { ...context, interface: 'apps' };
45
- if (!appCallGranted(byName.get(name), name, appContext, callGrant)) {
44
+ // The grant check sees the interface the call runs with, as in the core registry, and
45
+ // the call's dispatch id, made now so the grant reads the id the handler will
46
+ // (spec/dispatch.md, "The dispatch id"). The grant gets its own copy: the preset that
47
+ // carries the id to the engine is never handed to host code.
48
+ const dispatchId = createDispatchId();
49
+ const grantContext = { ...context, interface: 'apps' };
50
+ setDispatchId(grantContext, dispatchId);
51
+ if (!appCallGranted(byName.get(name), name, grantContext, callGrant)) {
46
52
  return failure(callNotGranted());
47
53
  }
54
+ const appContext = { ...context, interface: 'apps' };
55
+ presetDispatchId(appContext, dispatchId);
48
56
  return registry.execute(name, input, appContext, callOptions);
49
57
  },
50
58
  listTools: registry.listTools,
@@ -1 +1 @@
1
- {"version":3,"file":"app-call-registry.js","sourceRoot":"","sources":["../src/app-call-registry.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAuB,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EACN,cAAc,EAEd,cAAc,GACd,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACN,SAAS,EACT,oBAAoB,GAGpB,MAAM,sBAAsB,CAAC;AAc9B;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,qBAAqB,CACpC,QAAgC,EAChC,OAA+B;IAE/B,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;IACvC,IAAI,OAAO,SAAS,KAAK,UAAU,EAAE,CAAC;QACrC,MAAM,IAAI,SAAS,CAClB,gFAAgF,CAChF,CAAC;IACH,CAAC;IACD,2FAA2F;IAC3F,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,IAA6B,CAAC;IAC1F,MAAM,QAAQ,GAAG,oBAAoB,CAAC,QAAQ,EAAE;QAC/C,GAAG,MAAM;QACT,SAAS,EAAE,MAAiB;QAC5B,CAAC,SAAS,CAA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S,CAAC,EAAE,CAAC;gBACtE,OAAO,OAAO,CAAC,cAAc,EAAE,CAAC,CAAC;YAClC,CAAC;YACD,MAAM,UAAU,GAAmB,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC;YACrE,gBAAgB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;YACzC,OAAO,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;QAC/D,CAAC;QACD,SAAS,EAAE,QAAQ,CAAC,SAAS;QAC7B,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB;QAC3C,YAAY,EAAE,QAAQ,CAAC,YAAY;QACnC,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI;KACtB,CAAC;AACH,CAAC"}
@@ -23,12 +23,18 @@
23
23
  * this copy keeps its records to itself, so an admission from elsewhere is not honoured. This is
24
24
  * not a boundary against code running in the same process or page.
25
25
  */
26
- import type { ApprovalPolicy, CommandContext } from '@lushly-dev/afd-core';
26
+ import type { ApprovalPolicy, CommandContext, IdempotencySupport } from '@lushly-dev/afd-core';
27
27
  /** The command a call runs, as its admission record keeps it. */
28
28
  export interface AdmissionCommand {
29
29
  name: string;
30
30
  approval?: ApprovalPolicy<never>;
31
31
  confirmPrompt?: string;
32
+ /** The command's `secret` declaration, which the journal middleware reads. */
33
+ secret?: boolean;
34
+ /** The command's `mutation` declaration, which the retry middleware reads. */
35
+ mutation?: boolean;
36
+ /** The command's `idempotency` declaration, which the retry middleware reads. */
37
+ idempotency?: IdempotencySupport;
32
38
  }
33
39
  /** The canonical JSON of a value, or undefined when it has none. */
34
40
  export type Canonicalize = (value: unknown) => string | undefined;
@@ -90,4 +96,44 @@ export declare function livePolicy(context: CommandContext): {
90
96
  };
91
97
  /** The command the call of `context` runs, as recorded by the engine; undefined outside it. */
92
98
  export declare function liveCommand(context: CommandContext): AdmissionCommand | undefined;
99
+ /**
100
+ * Mark `inner` as the engine's when `outer` is: `composeMiddleware` builds continuations of its own
101
+ * for the parts it composes, and a part the engine reached through it is still the engine's.
102
+ */
103
+ export declare function inheritEngineNext(context: CommandContext, outer: object, inner: object): void;
104
+ /** Mark `next` as a continuation the engine built for the call of `context`. */
105
+ export declare function markEngineNext(context: CommandContext, next: object): void;
106
+ /**
107
+ * What the engine records of the call of `context`, for the journal: for a middleware the engine
108
+ * invoked (its `next` is one the engine built), and `undefined` for any other recorder: outside
109
+ * the engine, or one a handler runs itself on the same context, at any time. Its `secret` is
110
+ * whether the command declares `secret`, and its `token` is the call's identity, by which the
111
+ * journal tells a recorder of the same call from one of a call it runs inside.
112
+ */
113
+ export declare function liveDispatch(context: CommandContext, next: object): {
114
+ token: object;
115
+ secret: boolean;
116
+ } | undefined;
117
+ /**
118
+ * Whether the command the engine runs for `context` declares `mutation`, for the retry
119
+ * middleware: `true` or `false` for a middleware the engine invoked, and `undefined` for any other
120
+ * caller, as {@link liveDispatch} decides.
121
+ */
122
+ export declare function liveMutation(context: CommandContext, next: object): boolean | undefined;
123
+ /**
124
+ * The command's declaration and the call's key, for the retry middleware (`spec/idempotency.md`,
125
+ * R1): for a middleware the engine invoked, and `undefined` for any other caller, as
126
+ * {@link liveDispatch} decides.
127
+ */
128
+ export declare function liveRepeatDeclaration(context: CommandContext, next: object): {
129
+ mutation: boolean;
130
+ idempotency?: IdempotencySupport;
131
+ carriesKey: boolean;
132
+ } | undefined;
133
+ /** Record whether the call of `context` carries a key the retry middleware may count. */
134
+ export declare function recordCallKey(context: CommandContext, carriesKey: boolean): void;
135
+ /** Record that the idempotency step reserved the key of the call of `context` (R3). */
136
+ export declare function markIdempotencyStepActed(context: CommandContext): void;
137
+ /** Whether the idempotency step reserved the key of the call of `context` (R3). */
138
+ export declare function idempotencyStepActed(context: CommandContext): boolean;
93
139
  //# sourceMappingURL=approval-admission.d.ts.map