@lushly-dev/afd-server 2.5.0 → 3.1.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 (268) hide show
  1. package/README.md +100 -21
  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 +16 -2
  15. package/dist/approval-crypto.d.ts.map +1 -1
  16. package/dist/approval-crypto.js +45 -11
  17. package/dist/approval-crypto.js.map +1 -1
  18. package/dist/approval-process-state.d.ts +3 -0
  19. package/dist/approval-process-state.d.ts.map +1 -1
  20. package/dist/approval-process-state.js +2 -0
  21. package/dist/approval-process-state.js.map +1 -1
  22. package/dist/approval-relay.d.ts +41 -5
  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 +62 -13
  28. package/dist/approval-up-front.js.map +1 -1
  29. package/dist/approval.d.ts +55 -3
  30. package/dist/approval.d.ts.map +1 -1
  31. package/dist/approval.js +208 -54
  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 +44 -26
  65. package/dist/confirmation-gate.js.map +1 -1
  66. package/dist/confirmations.d.ts +46 -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 +30 -8
  86. package/dist/direct-registry.d.ts.map +1 -1
  87. package/dist/direct-registry.js +26 -5
  88. package/dist/direct-registry.js.map +1 -1
  89. package/dist/direct-tool-surface.d.ts +3 -1
  90. package/dist/direct-tool-surface.d.ts.map +1 -1
  91. package/dist/direct-tool-surface.js +22 -5
  92. package/dist/direct-tool-surface.js.map +1 -1
  93. package/dist/direct.d.ts +4 -2
  94. package/dist/direct.d.ts.map +1 -1
  95. package/dist/direct.js +2 -0
  96. package/dist/direct.js.map +1 -1
  97. package/dist/execution.d.ts +35 -6
  98. package/dist/execution.d.ts.map +1 -1
  99. package/dist/execution.js +108 -15
  100. package/dist/execution.js.map +1 -1
  101. package/dist/frontmatter.js +16 -13
  102. package/dist/frontmatter.js.map +1 -1
  103. package/dist/host-state.d.ts +96 -0
  104. package/dist/host-state.d.ts.map +1 -0
  105. package/dist/host-state.js +62 -0
  106. package/dist/host-state.js.map +1 -0
  107. package/dist/http-handler.d.ts +31 -12
  108. package/dist/http-handler.d.ts.map +1 -1
  109. package/dist/http-handler.js +138 -102
  110. package/dist/http-handler.js.map +1 -1
  111. package/dist/http-security.js +2 -2
  112. package/dist/http-security.js.map +1 -1
  113. package/dist/http-sessions.d.ts +10 -0
  114. package/dist/http-sessions.d.ts.map +1 -1
  115. package/dist/http-sessions.js +12 -2
  116. package/dist/http-sessions.js.map +1 -1
  117. package/dist/http-sse.d.ts +9 -0
  118. package/dist/http-sse.d.ts.map +1 -1
  119. package/dist/http-sse.js +12 -3
  120. package/dist/http-sse.js.map +1 -1
  121. package/dist/human-relay.d.ts +195 -0
  122. package/dist/human-relay.d.ts.map +1 -0
  123. package/dist/human-relay.js +697 -0
  124. package/dist/human-relay.js.map +1 -0
  125. package/dist/idempotency-step.d.ts +243 -0
  126. package/dist/idempotency-step.d.ts.map +1 -0
  127. package/dist/idempotency-step.js +419 -0
  128. package/dist/idempotency-step.js.map +1 -0
  129. package/dist/idempotency-store.d.ts +107 -0
  130. package/dist/idempotency-store.d.ts.map +1 -0
  131. package/dist/idempotency-store.js +100 -0
  132. package/dist/idempotency-store.js.map +1 -0
  133. package/dist/index.d.ts +10 -7
  134. package/dist/index.d.ts.map +1 -1
  135. package/dist/index.js +9 -5
  136. package/dist/index.js.map +1 -1
  137. package/dist/instance-state.d.ts +7 -0
  138. package/dist/instance-state.d.ts.map +1 -1
  139. package/dist/instance-state.js +5 -2
  140. package/dist/instance-state.js.map +1 -1
  141. package/dist/journal-off-tape.d.ts +52 -0
  142. package/dist/journal-off-tape.d.ts.map +1 -0
  143. package/dist/journal-off-tape.js +150 -0
  144. package/dist/journal-off-tape.js.map +1 -0
  145. package/dist/journal-replay.d.ts.map +1 -1
  146. package/dist/journal-replay.js +7 -0
  147. package/dist/journal-replay.js.map +1 -1
  148. package/dist/journal-view.d.ts +50 -0
  149. package/dist/journal-view.d.ts.map +1 -0
  150. package/dist/journal-view.js +214 -0
  151. package/dist/journal-view.js.map +1 -0
  152. package/dist/journal.d.ts +24 -5
  153. package/dist/journal.d.ts.map +1 -1
  154. package/dist/journal.js +91 -40
  155. package/dist/journal.js.map +1 -1
  156. package/dist/lazy-tools.d.ts +13 -3
  157. package/dist/lazy-tools.d.ts.map +1 -1
  158. package/dist/lazy-tools.js +9 -2
  159. package/dist/lazy-tools.js.map +1 -1
  160. package/dist/mcp-auth-dispatch.d.ts +1 -1
  161. package/dist/mcp-auth-dispatch.d.ts.map +1 -1
  162. package/dist/mcp-auth-dispatch.js +2 -1
  163. package/dist/mcp-auth-dispatch.js.map +1 -1
  164. package/dist/mcp-auth-jwt.d.ts +11 -4
  165. package/dist/mcp-auth-jwt.d.ts.map +1 -1
  166. package/dist/mcp-auth-jwt.js +11 -9
  167. package/dist/mcp-auth-jwt.js.map +1 -1
  168. package/dist/mcp-auth-resource.d.ts +27 -3
  169. package/dist/mcp-auth-resource.d.ts.map +1 -1
  170. package/dist/mcp-auth-resource.js +37 -10
  171. package/dist/mcp-auth-resource.js.map +1 -1
  172. package/dist/mcp-auth-rules.d.ts +97 -18
  173. package/dist/mcp-auth-rules.d.ts.map +1 -1
  174. package/dist/mcp-auth-rules.js +194 -37
  175. package/dist/mcp-auth-rules.js.map +1 -1
  176. package/dist/mcp-auth-view.d.ts +3 -3
  177. package/dist/mcp-auth-view.d.ts.map +1 -1
  178. package/dist/mcp-auth-view.js +62 -25
  179. package/dist/mcp-auth-view.js.map +1 -1
  180. package/dist/mcp-auth.d.ts +27 -4
  181. package/dist/mcp-auth.d.ts.map +1 -1
  182. package/dist/mcp-auth.js +55 -14
  183. package/dist/mcp-auth.js.map +1 -1
  184. package/dist/mcp-modern.d.ts +70 -7
  185. package/dist/mcp-modern.d.ts.map +1 -1
  186. package/dist/mcp-modern.js +225 -111
  187. package/dist/mcp-modern.js.map +1 -1
  188. package/dist/meta-argument.d.ts +2 -1
  189. package/dist/meta-argument.d.ts.map +1 -1
  190. package/dist/meta-argument.js +13 -2
  191. package/dist/meta-argument.js.map +1 -1
  192. package/dist/meta-tools.js +2 -2
  193. package/dist/meta-tools.js.map +1 -1
  194. package/dist/middleware.d.ts +18 -3
  195. package/dist/middleware.d.ts.map +1 -1
  196. package/dist/middleware.js +53 -7
  197. package/dist/middleware.js.map +1 -1
  198. package/dist/output-budget.d.ts.map +1 -1
  199. package/dist/output-budget.js +2 -0
  200. package/dist/output-budget.js.map +1 -1
  201. package/dist/principal-binding.js +1 -1
  202. package/dist/principal-binding.js.map +1 -1
  203. package/dist/relay-evidence.d.ts +74 -0
  204. package/dist/relay-evidence.d.ts.map +1 -0
  205. package/dist/relay-evidence.js +143 -0
  206. package/dist/relay-evidence.js.map +1 -0
  207. package/dist/request-context.d.ts +4 -0
  208. package/dist/request-context.d.ts.map +1 -1
  209. package/dist/request-context.js +12 -2
  210. package/dist/request-context.js.map +1 -1
  211. package/dist/resources.js +1 -1
  212. package/dist/resources.js.map +1 -1
  213. package/dist/schema.d.ts +4 -3
  214. package/dist/schema.d.ts.map +1 -1
  215. package/dist/schema.js +3 -3
  216. package/dist/schema.js.map +1 -1
  217. package/dist/scope-view.d.ts +18 -5
  218. package/dist/scope-view.d.ts.map +1 -1
  219. package/dist/scope-view.js +9 -8
  220. package/dist/scope-view.js.map +1 -1
  221. package/dist/server-types.d.ts +44 -16
  222. package/dist/server-types.d.ts.map +1 -1
  223. package/dist/server-types.js.map +1 -1
  224. package/dist/server.d.ts +26 -0
  225. package/dist/server.d.ts.map +1 -1
  226. package/dist/server.js +359 -89
  227. package/dist/server.js.map +1 -1
  228. package/dist/task-dispatch.d.ts +12 -6
  229. package/dist/task-dispatch.d.ts.map +1 -1
  230. package/dist/task-dispatch.js +11 -12
  231. package/dist/task-dispatch.js.map +1 -1
  232. package/dist/task-input.d.ts +29 -0
  233. package/dist/task-input.d.ts.map +1 -0
  234. package/dist/task-input.js +75 -0
  235. package/dist/task-input.js.map +1 -0
  236. package/dist/tasks-input-gate.d.ts +61 -0
  237. package/dist/tasks-input-gate.d.ts.map +1 -0
  238. package/dist/tasks-input-gate.js +325 -0
  239. package/dist/tasks-input-gate.js.map +1 -0
  240. package/dist/tasks-input-runner.d.ts +125 -0
  241. package/dist/tasks-input-runner.d.ts.map +1 -0
  242. package/dist/tasks-input-runner.js +1017 -0
  243. package/dist/tasks-input-runner.js.map +1 -0
  244. package/dist/tasks-runtime.d.ts +34 -7
  245. package/dist/tasks-runtime.d.ts.map +1 -1
  246. package/dist/tasks-runtime.js +545 -94
  247. package/dist/tasks-runtime.js.map +1 -1
  248. package/dist/tasks.d.ts +196 -25
  249. package/dist/tasks.d.ts.map +1 -1
  250. package/dist/tasks.js +188 -26
  251. package/dist/tasks.js.map +1 -1
  252. package/dist/tool-router.d.ts +62 -3
  253. package/dist/tool-router.d.ts.map +1 -1
  254. package/dist/tool-router.js +251 -101
  255. package/dist/tool-router.js.map +1 -1
  256. package/dist/tools.d.ts +32 -0
  257. package/dist/tools.d.ts.map +1 -1
  258. package/dist/tools.js +154 -40
  259. package/dist/tools.js.map +1 -1
  260. package/dist/up-front-steps.d.ts +8 -0
  261. package/dist/up-front-steps.d.ts.map +1 -1
  262. package/dist/up-front-steps.js +50 -1
  263. package/dist/up-front-steps.js.map +1 -1
  264. package/dist/validation.d.ts +14 -0
  265. package/dist/validation.d.ts.map +1 -1
  266. package/dist/validation.js +62 -17
  267. package/dist/validation.js.map +1 -1
  268. package/package.json +15 -11
@@ -6,17 +6,41 @@
6
6
  *
7
7
  * Used by both stdio and HTTP transports to eliminate routing duplication.
8
8
  */
9
- import { checkBatchLimits, createFailedBatchResult, failedBatchRequest, failure, isBatchRequest, isPipelineRequest, truncateName, } from '@lushly-dev/afd-core';
9
+ import { checkBatchLimits, createFailedBatchResult, failedBatchRequest, failure, invalidIdempotencyKeyError, isBatchRequest, isPipelineRequest, truncateName, } from '@lushly-dev/afd-core';
10
10
  import { commandNotAllowed } from '@lushly-dev/afd-core/internal/direct-allow';
11
+ import { traceIdEntropyError, tryCreateTraceId } from '@lushly-dev/afd-core/internal/dispatch-id';
12
+ import { resolveIdempotencyKey } from '@lushly-dev/afd-core/internal/idempotency';
11
13
  import { approvalRelay, bindUpFrontApproval, withoutApprovalRelay, } from './approval-relay.js';
12
14
  import { filterAllowed, isCommandAllowed } from './command-allow.js';
13
- import { commandAction, commandGroup, filterByContext, isAccessibleInContext, notFoundSuggestion, notInContextError, } from './command-routing.js';
14
- import { declaresConfirmInput, InputRequiredSignal, } from './confirmations.js';
15
+ import { canCall, commandAction, commandGroup, filterByContext, isAccessibleInContext, notFoundError, notFoundNext, notInContextError, } from './command-routing.js';
16
+ import { confirmationChannel, declaresConfirmInput, InputRequiredSignal, } from './confirmations.js';
15
17
  import { resolveContextState } from './context-scope.js';
16
18
  import { executeDetail, executeDiscover } from './lazy-tools.js';
17
19
  import { batchArgsSchema, callArgsSchema, checkMetaArgs, detailArgsSchema, discoverArgsSchema, parseMetaArgs, pipeArgsSchema, } from './meta-tools.js';
18
20
  import { knownOnly, listedCommands, scopeViewOf, shownOnly } from './scope-view.js';
19
21
  import { taskDispatchOf } from './task-dispatch.js';
22
+ /** A routing outcome carrying `value`. */
23
+ export function out(value, isError) {
24
+ return { kind: 'value', value, isError };
25
+ }
26
+ /** The MCP tool result of a routing outcome. */
27
+ export function toolResultOf(outcome) {
28
+ if (outcome.kind === 'tool')
29
+ return outcome.result;
30
+ if (outcome.kind === 'refused')
31
+ return resultContent(failure(outcome.error), true);
32
+ return resultContent(outcome.value, outcome.isError);
33
+ }
34
+ /** `router` as a {@link ToolRouter}: a plain function's results are already MCP tool results. */
35
+ export function asToolRouter(router) {
36
+ if ('route' in router)
37
+ return router;
38
+ const route = async (toolName, args, context = {}) => ({
39
+ kind: 'tool',
40
+ result: await router(toolName, (args ?? {}), context),
41
+ });
42
+ return Object.assign(async (toolName, args, context) => toolResultOf(await route(toolName, args, context)), { route });
43
+ }
20
44
  // ═══════════════════════════════════════════════════════════════════════════════
21
45
  // EMPTY PIPELINE RESULT (for invalid pipeline requests)
22
46
  // ═══════════════════════════════════════════════════════════════════════════════
@@ -45,6 +69,14 @@ function failedPipeline(error) {
45
69
  steps: [{ index: -1, command: '', status: 'failure', executionTimeMs: 0, error }],
46
70
  };
47
71
  }
72
+ /** A call refused before any command runs, shaped as its tool's own result. */
73
+ export function refusedCall(toolName, error) {
74
+ if (toolName === 'afd-batch')
75
+ return out(createFailedBatchResult(error, {}), true);
76
+ if (toolName === 'afd-pipe')
77
+ return out(failedPipeline(error), true);
78
+ return out(failure(error), true);
79
+ }
48
80
  /**
49
81
  * Wrap a result as MCP tool content. The JSON is compact: the text is read by an
50
82
  * agent, and indentation only adds tokens.
@@ -75,12 +107,14 @@ function withoutConfirm(args) {
75
107
  /**
76
108
  * The `COMMAND_NOT_IN_CONTEXT` tool result when `cmd` exists but is outside the
77
109
  * active context; undefined otherwise (a missing command is left to execution).
110
+ *
111
+ * @param can - Whether the caller can call a command, for the suggestion and recovery
78
112
  */
79
- function contextDenial(cmd, commandName, contextState) {
113
+ function contextDenial(cmd, commandName, contextState, can) {
80
114
  const activeContext = contextState?.getActive();
81
115
  if (!cmd || !activeContext || isAccessibleInContext(cmd, activeContext))
82
116
  return undefined;
83
- return resultContent({ success: false, error: notInContextError(commandName, activeContext) }, true);
117
+ return out({ success: false, error: notInContextError(commandName, activeContext, cmd.contexts, can) }, true);
84
118
  }
85
119
  /**
86
120
  * The `COMMAND_NOT_ALLOWED` tool result when the `allow` option of a direct registry call refuses
@@ -89,7 +123,7 @@ function contextDenial(cmd, commandName, contextState) {
89
123
  function allowDenial(commandName, callContext) {
90
124
  if (isCommandAllowed(callContext, commandName))
91
125
  return undefined;
92
- return resultContent(failure(commandNotAllowed(commandName)), true);
126
+ return out(failure(commandNotAllowed(commandName)), true);
93
127
  }
94
128
  /**
95
129
  * Create a tool call router that dispatches to the appropriate execution function.
@@ -100,44 +134,130 @@ function allowDenial(commandName, callContext) {
100
134
  */
101
135
  export function createToolRouter(deps) {
102
136
  const { executeCommand, executeBatch, executePipeline, toolStrategy, groupByFn, devMode } = deps;
137
+ const engineRun = async (name, input, context) => {
138
+ const result = await executeCommand(name, input, context);
139
+ return out(result, !result.success);
140
+ };
141
+ // Built once (#1746), so a call looks its command up instead of scanning every command. The
142
+ // first command of a name wins, as `find` would pick it.
143
+ const commandsByName = new Map();
144
+ for (const command of deps.commands) {
145
+ if (!commandsByName.has(command.name))
146
+ commandsByName.set(command.name, command);
147
+ }
148
+ /**
149
+ * The commands' groups, in command order: built at the first grouped call, which calls
150
+ * `groupByFn` once per command, so it must answer the same for the same command.
151
+ */
152
+ let groups;
153
+ const groupMembers = (group) => {
154
+ if (!groups) {
155
+ const built = new Map();
156
+ for (const command of deps.commands) {
157
+ const name = commandGroup(command, groupByFn);
158
+ const members = built.get(name);
159
+ if (members)
160
+ members.push(command);
161
+ else
162
+ built.set(name, [command]);
163
+ }
164
+ groups = built;
165
+ }
166
+ return groups.get(group) ?? [];
167
+ };
103
168
  /**
104
169
  * Route one tool call.
105
170
  *
106
171
  * @param callContext - Base `CommandContext` for commands this call runs (request values,
107
172
  * `signal`, and the caller's context state); each execution adds its own `traceId`.
108
173
  */
109
- return async function routeToolCall(toolName, args, callContext = {}) {
174
+ async function route(toolName, args, callContext = {}, run = engineRun) {
110
175
  const contextState = resolveContextState(callContext, deps.contextState);
111
176
  const gate = deps.confirmations;
112
177
  /**
113
178
  * Check confirmations; `undefined` means the call may run. An elicitation is thrown as an
114
179
  * {@link InputRequiredSignal}, which only a lane that bound an eliciting channel catches.
115
180
  */
116
- const confirm = async (steps, acknowledged, howToAcknowledge, toResult = (outcome) => resultContent({ success: false, error: outcome.error }, true)) => {
181
+ const confirm = async (steps, acknowledged, howToAcknowledge, toResult = (outcome) => out({ success: false, error: outcome.error }, true)) => {
182
+ // The key before confirmation (spec/dispatch.md, "The idempotency step"): a malformed one,
183
+ // and a keyed call the server cannot tell apart, are refused here (K2, S3).
184
+ const refusal = idempotencyRefusal(steps);
185
+ if (refusal)
186
+ return toResult({ kind: 'error', error: refusal });
117
187
  if (!gate || gate.mode === 'off')
118
188
  return undefined;
119
- const outcome = await gate.check(steps, acknowledged, callContext, howToAcknowledge);
189
+ // A lane whose acknowledgement is not an argument (the HTTP routes' `Afd-Confirm`
190
+ // header) says what it acknowledges and how to send it; an argument counts for nothing.
191
+ const byLane = confirmationChannel(callContext)?.acknowledgement;
192
+ const outcome = await gate.check(steps, byLane ? byLane.names : acknowledged, callContext, byLane
193
+ ? byLane.how([...new Set(gate.gated(steps).map((step) => step.command))])
194
+ : howToAcknowledge);
120
195
  if (outcome.kind === 'proceed')
121
196
  return undefined;
122
197
  if (outcome.kind === 'input-required')
123
198
  throw new InputRequiredSignal(outcome.result);
124
199
  return toResult(outcome);
125
200
  };
126
- const traced = (prefix) => ({
127
- ...callContext,
128
- traceId: `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`,
129
- });
201
+ /**
202
+ * The refusal of a call's idempotency key before confirmation, or `undefined`: K2's form, and
203
+ * S3 for a step that names a `keyed` command on a server with the idempotency step. Credentials
204
+ * the step cannot bind are thrown to the lane, which answers an internal error.
205
+ */
206
+ function idempotencyRefusal(steps) {
207
+ // Decided as the engine decides it: a key the outer handler was given is none (K6), and a
208
+ // derived or restored one is the engine's.
209
+ const key = resolveIdempotencyKey(callContext);
210
+ if (key.kind === 'none')
211
+ return undefined;
212
+ if (key.kind === 'invalid')
213
+ return invalidIdempotencyKeyError();
214
+ const step = deps.idempotency;
215
+ if (!step || !steps.some((entry) => lookup(entry.command)?.idempotency === 'keyed')) {
216
+ return undefined;
217
+ }
218
+ const decided = step.principal(callContext);
219
+ if (decided.kind === 'refused')
220
+ return decided.error;
221
+ if (decided.kind === 'internal') {
222
+ throw new Error(step.internalError().message);
223
+ }
224
+ return undefined;
225
+ }
226
+ const traced = () => {
227
+ const traceId = callContext.traceId || tryCreateTraceId();
228
+ return traceId ? { ...callContext, traceId } : undefined;
229
+ };
230
+ const runHostVerified = async (cmd, input) => {
231
+ if (!deps.humanRelay || cmd?.confirmationMode !== 'host-verified')
232
+ return undefined;
233
+ // Before the person is asked, as before confirmation (spec/idempotency.md, K2, S3).
234
+ const refusal = idempotencyRefusal([{ command: cmd.name }]);
235
+ if (refusal)
236
+ return out(failure(refusal), true);
237
+ const ctx = traced();
238
+ if (!ctx)
239
+ return out(failure(traceIdEntropyError()), true);
240
+ const outcome = await deps.humanRelay.check(cmd, input, ctx);
241
+ if (outcome.kind === 'input-required')
242
+ throw new InputRequiredSignal(outcome.result);
243
+ if (outcome.kind === 'error')
244
+ return out(failure(outcome.error), true);
245
+ return run(cmd.name, input, outcome.context);
246
+ };
130
247
  /**
131
248
  * The context of a batch's or pipeline's steps. Steps cannot ask for approval mid-run (the
132
249
  * retry would run the earlier steps again), so a call that can ask is approved up front, as
133
250
  * a whole, before any step runs (#459). Only the MCP lane's relay offers that.
134
251
  */
135
- const stepsContext = (tool, prefix, request) => {
252
+ const stepsContext = (tool, request) => {
253
+ const ctx = traced();
254
+ if (!ctx)
255
+ return undefined;
136
256
  const relay = approvalRelay(callContext);
137
257
  if (!relay)
138
- return { context: traced(prefix) };
139
- const steps = withoutApprovalRelay(traced(prefix));
140
- const upFront = relay.upFront?.(tool, request, commands);
258
+ return { context: ctx };
259
+ const steps = withoutApprovalRelay(ctx);
260
+ const upFront = relay.upFront?.(tool, request, commands());
141
261
  return upFront
142
262
  ? { context: bindUpFrontApproval(steps, upFront), upFront }
143
263
  : { context: steps };
@@ -149,89 +269,110 @@ export function createToolRouter(deps) {
149
269
  const view = scopeViewOf(callContext);
150
270
  const decision = view?.decideCall(toolName, args);
151
271
  if (view && decision && decision !== 'proceed') {
152
- const error = view.insufficientScope(decision.forbidden);
153
- if (toolName === 'afd-batch')
154
- return resultContent(createFailedBatchResult(error, {}), true);
155
- if (toolName === 'afd-pipe')
156
- return resultContent(failedPipeline(error), true);
157
- return resultContent(failure(error), true);
272
+ return refusedCall(toolName, view.insufficientScope(decision.forbidden));
158
273
  }
159
- const commands = knownOnly(deps.commands, callContext);
160
- const allCommands = deps.allCommands && knownOnly(deps.allCommands, callContext);
274
+ // The commands that exist for the caller: every command without a view. A view's list is
275
+ // filtered only when a route needs it, and one command is looked up by name.
276
+ let known;
277
+ const commands = () => {
278
+ known ??= knownOnly(deps.commands, callContext);
279
+ return known;
280
+ };
281
+ const lookup = (name) => {
282
+ const command = commandsByName.get(name);
283
+ return command && (!view || view.known(name)) ? command : undefined;
284
+ };
285
+ // Whether the caller can call a command, decided once for each refusal's suggestion and
286
+ // recovery (`spec/recovery.md`, "Engine errors"). The router serves every meta-tool.
287
+ const surface = {
288
+ metaTools: deps.metaTools ?? true,
289
+ command: lookup,
290
+ ...(view && { shown: (name) => view.shown(name) }),
291
+ };
292
+ const can = (name) => canCall(surface, name, callContext, contextState?.getActive());
161
293
  const exposedCommandNames = deps.exposedCommandNames;
162
294
  /** The steps naming commands that exist for the caller: a confirmation names no other. */
163
295
  const existing = (steps) => view ? steps.filter((step) => view.known(step.command)) : steps;
164
296
  const taskDispatch = taskDispatchOf(callContext);
165
- const runTask = (cmd, input, prefix) => taskDispatch && (cmd?.task === 'optional' || cmd?.task === 'required')
166
- ? taskDispatch.dispatch(cmd, input, traced(prefix))
167
- : undefined;
297
+ const runSingle = async (cmd, name, input, acknowledged, howToAcknowledge) => {
298
+ if (taskDispatch && (cmd?.task === 'optional' || cmd?.task === 'required')) {
299
+ const refusal = idempotencyRefusal([{ command: cmd.name }]);
300
+ if (refusal)
301
+ return out(failure(refusal), true);
302
+ const taskCtx = traced();
303
+ if (!taskCtx)
304
+ return out(failure(traceIdEntropyError()), true);
305
+ const result = await taskDispatch.dispatch(cmd, input, taskCtx, {
306
+ acknowledged,
307
+ howToAcknowledge,
308
+ });
309
+ if (result)
310
+ return { kind: 'tool', result };
311
+ }
312
+ const hostVerified = await runHostVerified(cmd, input);
313
+ if (hostVerified)
314
+ return hostVerified;
315
+ const unconfirmed = await confirm(existing([{ command: name, input }]), acknowledged, howToAcknowledge);
316
+ if (unconfirmed)
317
+ return unconfirmed;
318
+ const ctx = traced();
319
+ if (!ctx)
320
+ return out(failure(traceIdEntropyError()), true);
321
+ approvalRelay(callContext)?.route(name);
322
+ return run(name, input, ctx);
323
+ };
168
324
  const requiredTaskIn = (steps) => taskDispatch
169
325
  ? existing([...steps])
170
- .map((s) => commands.find((c) => c.name === s.command))
326
+ .map((s) => lookup(s.command))
171
327
  .find((c) => c?.task === 'required')
172
328
  : undefined;
173
329
  // Handle afd-call (available in all strategies)
174
330
  if (toolName === 'afd-call') {
175
331
  const parsed = parseMetaArgs(toolName, callArgsSchema, args, 'Provide { command: "command-name", input: {...} }');
176
332
  if (!parsed.success)
177
- return resultContent(parsed.result, true);
333
+ return out(parsed.result, true);
178
334
  const { command: commandName, input, confirm: confirmArg } = parsed.data;
179
335
  // Before the lookup, so a refused name gives the same answer whether it exists.
180
336
  const refused = allowDenial(commandName, callContext);
181
337
  if (refused)
182
338
  return refused;
183
339
  // Check if command exists in the exposed commands
184
- const cmd = commands.find((c) => c.name === commandName);
340
+ const cmd = lookup(commandName);
185
341
  if (!cmd) {
186
342
  // An unexposed command gets the same answer as an unknown one, so a remote
187
343
  // caller cannot learn that a private command exists (spec/error-codes.md, D4).
188
344
  // Suggest a few close matches the caller can use.
189
- const callable = filterAllowed(filterByContext(shownOnly(commands, callContext), contextState?.getActive()), callContext);
190
- return resultContent({
191
- success: false,
192
- error: {
193
- code: 'COMMAND_NOT_FOUND',
194
- message: `Command '${truncateName(commandName)}' not found`,
195
- suggestion: notFoundSuggestion(commandName, callable.map((c) => c.name)),
196
- },
197
- }, true);
345
+ const callable = filterAllowed(filterByContext(shownOnly(commands(), callContext), contextState?.getActive()), callContext);
346
+ return out(failure(notFoundError(commandName, callable.map((c) => c.name), notFoundNext(can))), true);
198
347
  }
199
348
  // Context check: validate the command is accessible in current context
200
- const denied = contextDenial(cmd, commandName, contextState);
349
+ const denied = contextDenial(cmd, commandName, contextState, can);
201
350
  if (denied)
202
351
  return denied;
203
- const unconfirmed = await confirm([{ command: commandName, input: input ?? {} }], confirmArg === true ? 'all' : undefined, 'repeat the afd-call with confirm: true');
204
- if (unconfirmed)
205
- return unconfirmed;
206
- const dispatched = await runTask(cmd, input ?? {}, 'afd-call');
207
- if (dispatched)
208
- return dispatched;
209
- // Execute through the execution engine (full middleware chain)
210
- approvalRelay(callContext)?.route(commandName);
211
- const result = await executeCommand(commandName, input ?? {}, traced('afd-call'));
212
- return resultContent(result, !result.success);
352
+ return runSingle(cmd, commandName, input ?? {}, confirmArg === true ? 'all' : undefined, 'repeat the afd-call with confirm: true');
213
353
  }
214
354
  // Handle afd-discover (listed by the lazy strategy, routable in all)
215
355
  if (toolName === 'afd-discover') {
216
356
  const parsed = parseMetaArgs(toolName, discoverArgsSchema, args, 'Provide optional { category, tag, tagMode, search, includeMutation, limit, offset }');
217
357
  if (!parsed.success)
218
- return resultContent(parsed.result, true);
358
+ return out(parsed.result, true);
219
359
  // Filter by active context when context state is available, and by the call's `allow`
220
- const discoverCommands = filterAllowed(filterByContext(listedCommands(commands, callContext), contextState?.getActive()), callContext);
360
+ const discoverCommands = filterAllowed(filterByContext(listedCommands(commands(), callContext), contextState?.getActive()), callContext);
221
361
  const result = executeDiscover(discoverCommands, parsed.data);
222
- return resultContent(result, false);
362
+ return out(result, false);
223
363
  }
224
364
  // Handle afd-detail (listed by the lazy and grouped strategies, routable in all)
225
365
  if (toolName === 'afd-detail') {
226
366
  const parsed = parseMetaArgs(toolName, detailArgsSchema, args, 'Provide { command: "command-name" } or { command: ["name-1", "name-2"] } (max 10)');
227
367
  if (!parsed.success)
228
- return resultContent(parsed.result, true);
229
- const exposedNames = exposedCommandNames ?? new Set(commands.map((c) => c.name));
368
+ return out(parsed.result, true);
369
+ const exposedNames = exposedCommandNames ?? new Set(commands().map((c) => c.name));
370
+ const allCommands = deps.allCommands && knownOnly(deps.allCommands, callContext);
230
371
  // Filter by active context so agents cannot inspect commands outside their context, and
231
372
  // by the call's `allow`, so a refused command reads as unknown
232
- const contextFilteredCmds = filterAllowed(filterByContext(listedCommands(allCommands ?? commands, callContext), contextState?.getActive()), callContext);
233
- const result = executeDetail(contextFilteredCmds, exposedNames, parsed.data);
234
- return resultContent(result, false);
373
+ const contextFilteredCmds = filterAllowed(filterByContext(listedCommands(allCommands ?? commands(), callContext), contextState?.getActive()), callContext);
374
+ const result = executeDetail(contextFilteredCmds, exposedNames, parsed.data, notFoundNext(can));
375
+ return out(result, false);
235
376
  }
236
377
  // Handle built-in afd-batch tool
237
378
  if (toolName === 'afd-batch') {
@@ -240,31 +381,38 @@ export function createToolRouter(deps) {
240
381
  const check = checkMetaArgs(batchArgsSchema, args);
241
382
  if (!check.success || !isBatchRequest(args)) {
242
383
  const usage = 'Provide { commands: [...] } with command objects';
243
- return resultContent(failedBatchRequest({}, check.success ? undefined : { errors: check.errors }, check.success ? usage : `${check.suggestion}. ${usage}`), true);
384
+ return out(failedBatchRequest({}, check.success ? undefined : { errors: check.errors }, check.success ? usage : `${check.suggestion}. ${usage}`), true);
244
385
  }
245
386
  const limitError = checkBatchLimits(args, {
246
387
  maxBatchSize: deps.maxBatchSize,
247
388
  maxBatchParallelism: deps.maxBatchParallelism,
248
389
  });
249
390
  if (limitError) {
250
- return resultContent(createFailedBatchResult(limitError, {}), true);
391
+ return out(createFailedBatchResult(limitError, {}), true);
251
392
  }
252
393
  const batchArgs = args;
253
394
  const requiredBatch = requiredTaskIn(args.commands);
254
395
  if (requiredBatch && taskDispatch) {
255
- return resultContent(createFailedBatchResult(taskDispatch.refuseComposite('afd-batch', requiredBatch.name), {}), true);
396
+ return out(createFailedBatchResult(taskDispatch.refuseComposite('afd-batch', requiredBatch.name), {}), true);
397
+ }
398
+ const batchSteps = existing(args.commands.map((item) => ({ command: item.command, input: item.input ?? {} })));
399
+ const hostVerifiedBatch = deps.humanRelay?.refuseSteps(batchSteps);
400
+ if (hostVerifiedBatch) {
401
+ return out(createFailedBatchResult(hostVerifiedBatch, {}), true);
256
402
  }
257
- const unconfirmed = await confirm(existing(args.commands.map((item) => ({ command: item.command, input: item.input ?? {} }))), namedAcknowledgement(batchArgs.confirm), 'repeat the afd-batch with confirm: [the command names]', (outcome) => resultContent(createFailedBatchResult(outcome.error, {}), true));
403
+ const unconfirmed = await confirm(batchSteps, namedAcknowledgement(batchArgs.confirm), 'repeat the afd-batch with confirm: [the command names]', (outcome) => out(createFailedBatchResult(outcome.error, {}), true));
258
404
  if (unconfirmed)
259
405
  return unconfirmed;
260
406
  const request = withoutConfirm(args);
261
- const steps = stepsContext('afd-batch', 'batch', request);
407
+ const steps = stepsContext('afd-batch', request);
408
+ if (!steps)
409
+ return out(createFailedBatchResult(traceIdEntropyError(), {}), true);
262
410
  const result = await executeBatch(request, steps.context);
263
411
  // Nothing ran: the whole batch was refused, or waits for the user's approval.
264
412
  const refusal = steps.upFront?.refusal;
265
413
  if (refusal)
266
- return resultContent(createFailedBatchResult(refusal, {}), true);
267
- return resultContent(result, !result.success);
414
+ return out(createFailedBatchResult(refusal, {}), true);
415
+ return out(result, !result.success);
268
416
  }
269
417
  // Handle built-in afd-pipe tool
270
418
  if (toolName === 'afd-pipe') {
@@ -273,7 +421,7 @@ export function createToolRouter(deps) {
273
421
  const check = checkMetaArgs(pipeArgsSchema, args);
274
422
  if (!check.success || !isPipelineRequest(args)) {
275
423
  const usage = 'Provide steps with nonempty command names, object inputs, valid conditions, and correctly typed options; input must be JSON';
276
- return resultContent({
424
+ return out({
277
425
  ...emptyPipelineResult,
278
426
  steps: [
279
427
  {
@@ -294,22 +442,33 @@ export function createToolRouter(deps) {
294
442
  const pipeArgs = args;
295
443
  const requiredPipe = requiredTaskIn(args.steps);
296
444
  if (requiredPipe && taskDispatch) {
297
- return resultContent(failedPipeline(taskDispatch.refuseComposite('afd-pipe', requiredPipe.name)), true);
445
+ return out(failedPipeline(taskDispatch.refuseComposite('afd-pipe', requiredPipe.name)), true);
298
446
  }
299
- const unconfirmed = await confirm(existing(args.steps.map((step) => ({ command: step.command, input: step.input ?? {} }))), namedAcknowledgement(pipeArgs.confirm), 'repeat the afd-pipe with confirm: [the command names]', (outcome) => resultContent(failedPipeline(outcome.error), true));
447
+ const pipeSteps = existing(args.steps.map((step) => ({ command: step.command, input: step.input ?? {} })));
448
+ const hostVerifiedPipe = deps.humanRelay?.refuseSteps(pipeSteps);
449
+ if (hostVerifiedPipe) {
450
+ return out(failedPipeline(hostVerifiedPipe), true);
451
+ }
452
+ const unconfirmed = await confirm(pipeSteps, namedAcknowledgement(pipeArgs.confirm), 'repeat the afd-pipe with confirm: [the command names]', (outcome) => out(failedPipeline(outcome.error), true));
300
453
  if (unconfirmed)
301
454
  return unconfirmed;
302
455
  const request = withoutConfirm(args);
303
- const steps = stepsContext('afd-pipe', 'pipeline', request);
456
+ const steps = stepsContext('afd-pipe', request);
457
+ if (!steps)
458
+ return out(failedPipeline(traceIdEntropyError()), true);
304
459
  const result = await executePipeline(request, steps.context);
305
460
  const refusal = steps.upFront?.refusal;
306
461
  if (refusal)
307
- return resultContent(failedPipeline(refusal), true);
462
+ return out(failedPipeline(refusal), true);
308
463
  const hasFailed = result.steps.some((s) => s.status === 'failure');
309
- return resultContent(result, hasFailed);
464
+ return out(result, hasFailed);
310
465
  }
311
- // Handle grouped tool calls (when toolStrategy === "grouped")
312
- if (toolStrategy === 'grouped') {
466
+ // Handle grouped tool calls: under `grouped`, and under every other strategy for a group name
467
+ // no command the caller knows has, with a member the caller knows, so a call to a grouped tool
468
+ // keeps working whichever list is served (#2632). Hidden commands decide nothing: a group
469
+ // whose members are all hidden is a name that does not exist (M6).
470
+ if (toolStrategy === 'grouped' ||
471
+ (!lookup(toolName) && knownOnly(groupMembers(toolName), callContext).length > 0)) {
313
472
  const typedArgs = args;
314
473
  const action = typedArgs?.action;
315
474
  const commandParams = typedArgs?.params ?? {};
@@ -318,15 +477,15 @@ export function createToolRouter(deps) {
318
477
  }
319
478
  // Only the commands the call's `allow` permits, so a refused command is invisible here: it
320
479
  // cannot make an action ambiguous, and a group with none left is refused as a whole.
321
- const groupCommands = commands.filter((cmd) => commandGroup(cmd, groupByFn) === toolName);
480
+ const groupCommands = knownOnly(groupMembers(toolName), callContext);
322
481
  const allowedGroupCommands = filterAllowed(groupCommands, callContext);
323
482
  if (groupCommands.length > 0 && allowedGroupCommands.length === 0) {
324
- return resultContent(failure(commandNotAllowed(toolName)), true);
483
+ return out(failure(commandNotAllowed(toolName)), true);
325
484
  }
326
485
  if (action && typeof action === 'string') {
327
486
  const candidates = allowedGroupCommands.filter((command) => commandAction(command) === action);
328
487
  if (candidates.length !== 1) {
329
- return resultContent(failure({
488
+ return out(failure({
330
489
  code: candidates.length ? 'AMBIGUOUS_ACTION' : 'COMMAND_NOT_FOUND',
331
490
  message: `Action '${truncateName(action)}' does not identify one command in group '${truncateName(toolName)}'`,
332
491
  suggestion: 'Use afd-call with the full command name, or list tools to find a valid action.',
@@ -337,18 +496,10 @@ export function createToolRouter(deps) {
337
496
  if (refused)
338
497
  return refused;
339
498
  // Context check for grouped strategy
340
- const denied = contextDenial(candidates[0], actualCommandName, contextState);
499
+ const denied = contextDenial(candidates[0], actualCommandName, contextState, can);
341
500
  if (denied)
342
501
  return denied;
343
- const unconfirmed = await confirm([{ command: actualCommandName, input: commandParams }], typedArgs?.confirm === true ? 'all' : undefined, `repeat the ${toolName} call with confirm: true`);
344
- if (unconfirmed)
345
- return unconfirmed;
346
- const dispatched = await runTask(candidates[0], commandParams, 'trace');
347
- if (dispatched)
348
- return dispatched;
349
- approvalRelay(callContext)?.route(actualCommandName);
350
- const result = await executeCommand(actualCommandName, commandParams, traced('trace'));
351
- return resultContent(result, !result.success);
502
+ return runSingle(candidates[0], actualCommandName, commandParams, typedArgs?.confirm === true ? 'all' : undefined, `repeat the ${toolName} call with confirm: true`);
352
503
  }
353
504
  // In grouped mode, if tool is a known group but action is missing/invalid,
354
505
  // return a helpful error instead of falling through. Only a group with a member the
@@ -356,7 +507,7 @@ export function createToolRouter(deps) {
356
507
  const shownGroupCommands = shownOnly(allowedGroupCommands, callContext);
357
508
  if (shownGroupCommands.length > 0) {
358
509
  const availableActions = shownGroupCommands.map(commandAction);
359
- return resultContent({
510
+ return out({
360
511
  success: false,
361
512
  error: {
362
513
  code: 'INVALID_GROUPED_CALL',
@@ -372,28 +523,27 @@ export function createToolRouter(deps) {
372
523
  if (refused)
373
524
  return refused;
374
525
  // Context check: validate the command is accessible in current context
375
- const command = commands.find((c) => c.name === toolName);
376
- const denied = contextDenial(command, toolName, contextState);
526
+ const command = lookup(toolName);
527
+ const denied = contextDenial(command, toolName, contextState, can);
377
528
  if (denied)
378
529
  return denied;
379
530
  // A confirm-gated tool advertises an optional `confirm` argument, removed here before the
380
531
  // command validates its input, unless the command's own schema declares `confirm`.
532
+ // A host-verified command never advertises or accepts `confirm`, so its input is left intact.
381
533
  let input = args ?? {};
382
534
  let acknowledged;
383
- if (gate && gate.mode !== 'off' && command?.confirmPrompt && isRecord(input)) {
535
+ if (gate &&
536
+ gate.mode !== 'off' &&
537
+ command?.confirmPrompt &&
538
+ command.confirmationMode !== 'host-verified' &&
539
+ isRecord(input)) {
384
540
  acknowledged = input.confirm === true ? 'all' : undefined;
385
541
  if (!declaresConfirmInput(command))
386
542
  input = withoutConfirm(input);
387
543
  }
388
- const unconfirmed = await confirm(existing([{ command: toolName, input }]), acknowledged, 'repeat the call with confirm: true');
389
- if (unconfirmed)
390
- return unconfirmed;
391
- const dispatched = await runTask(command, input, 'trace');
392
- if (dispatched)
393
- return dispatched;
394
- approvalRelay(callContext)?.route(toolName);
395
- const result = await executeCommand(toolName, input, traced('trace'));
396
- return resultContent(result, !result.success);
397
- };
544
+ return runSingle(command, toolName, input, acknowledged, 'repeat the call with confirm: true');
545
+ }
546
+ const routeToolCall = async (toolName, args, callContext) => toolResultOf(await route(toolName, args, callContext));
547
+ return Object.assign(routeToolCall, { route });
398
548
  }
399
549
  //# sourceMappingURL=tool-router.js.map