@stigmer/runner 3.9.0 → 3.11.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 (270) hide show
  1. package/README.md +12 -1
  2. package/dist/.build-fingerprint +1 -1
  3. package/dist/activities/call-llm.js +9 -10
  4. package/dist/activities/call-llm.js.map +1 -1
  5. package/dist/activities/classify-tool-approvals.d.ts +2 -1
  6. package/dist/activities/classify-tool-approvals.js +28 -2
  7. package/dist/activities/classify-tool-approvals.js.map +1 -1
  8. package/dist/activities/discover-mcp-server.d.ts +32 -0
  9. package/dist/activities/discover-mcp-server.js +162 -27
  10. package/dist/activities/discover-mcp-server.js.map +1 -1
  11. package/dist/activities/execute-cursor/__test-utils__/cursor-hook-harness.d.ts +8 -0
  12. package/dist/activities/execute-cursor/__test-utils__/cursor-hook-harness.js +1 -1
  13. package/dist/activities/execute-cursor/__test-utils__/cursor-hook-harness.js.map +1 -1
  14. package/dist/activities/execute-cursor/approval-state.d.ts +28 -2
  15. package/dist/activities/execute-cursor/approval-state.js +7 -1
  16. package/dist/activities/execute-cursor/approval-state.js.map +1 -1
  17. package/dist/activities/execute-cursor/attachment-resolver.d.ts +14 -0
  18. package/dist/activities/execute-cursor/attachment-resolver.js +25 -4
  19. package/dist/activities/execute-cursor/attachment-resolver.js.map +1 -1
  20. package/dist/activities/execute-cursor/blueprint-resolver.d.ts +1 -9
  21. package/dist/activities/execute-cursor/blueprint-resolver.js +6 -22
  22. package/dist/activities/execute-cursor/blueprint-resolver.js.map +1 -1
  23. package/dist/activities/execute-cursor/env-resolver.js +3 -1
  24. package/dist/activities/execute-cursor/env-resolver.js.map +1 -1
  25. package/dist/activities/execute-cursor/error-classifier.d.ts +40 -3
  26. package/dist/activities/execute-cursor/error-classifier.js +81 -3
  27. package/dist/activities/execute-cursor/error-classifier.js.map +1 -1
  28. package/dist/activities/execute-cursor/extract-structured-output.d.ts +29 -0
  29. package/dist/activities/execute-cursor/extract-structured-output.js +58 -0
  30. package/dist/activities/execute-cursor/extract-structured-output.js.map +1 -0
  31. package/dist/activities/execute-cursor/hook-script.d.ts +14 -3
  32. package/dist/activities/execute-cursor/hook-script.js +72 -10
  33. package/dist/activities/execute-cursor/hook-script.js.map +1 -1
  34. package/dist/activities/execute-cursor/index.d.ts +5 -1
  35. package/dist/activities/execute-cursor/index.js +59 -58
  36. package/dist/activities/execute-cursor/index.js.map +1 -1
  37. package/dist/activities/execute-cursor/mcp-resolver.d.ts +24 -1
  38. package/dist/activities/execute-cursor/mcp-resolver.js +5 -2
  39. package/dist/activities/execute-cursor/mcp-resolver.js.map +1 -1
  40. package/dist/activities/execute-cursor/prompt-builder.d.ts +18 -4
  41. package/dist/activities/execute-cursor/prompt-builder.js +12 -7
  42. package/dist/activities/execute-cursor/prompt-builder.js.map +1 -1
  43. package/dist/activities/execute-cursor/turn-stream.js +4 -1
  44. package/dist/activities/execute-cursor/turn-stream.js.map +1 -1
  45. package/dist/activities/execute-deep-agent/attachment-injector.d.ts +18 -1
  46. package/dist/activities/execute-deep-agent/attachment-injector.js +68 -23
  47. package/dist/activities/execute-deep-agent/attachment-injector.js.map +1 -1
  48. package/dist/activities/execute-deep-agent/environment.js +3 -1
  49. package/dist/activities/execute-deep-agent/environment.js.map +1 -1
  50. package/dist/activities/execute-deep-agent/index.js +15 -0
  51. package/dist/activities/execute-deep-agent/index.js.map +1 -1
  52. package/dist/activities/execute-deep-agent/prompt-builder.d.ts +7 -7
  53. package/dist/activities/execute-deep-agent/prompt-builder.js +8 -2
  54. package/dist/activities/execute-deep-agent/prompt-builder.js.map +1 -1
  55. package/dist/activities/execute-deep-agent/setup.d.ts +10 -0
  56. package/dist/activities/execute-deep-agent/setup.js +65 -26
  57. package/dist/activities/execute-deep-agent/setup.js.map +1 -1
  58. package/dist/activities/execute-deep-agent/subagent-transformer.d.ts +18 -1
  59. package/dist/activities/execute-deep-agent/subagent-transformer.js +8 -1
  60. package/dist/activities/execute-deep-agent/subagent-transformer.js.map +1 -1
  61. package/dist/activities/execute-deep-agent/subagent-wiring.d.ts +11 -4
  62. package/dist/activities/execute-deep-agent/subagent-wiring.js +13 -4
  63. package/dist/activities/execute-deep-agent/subagent-wiring.js.map +1 -1
  64. package/dist/activities/hydrate-workflow-execution.js +3 -1
  65. package/dist/activities/hydrate-workflow-execution.js.map +1 -1
  66. package/dist/activities/workflow-event-activities.d.ts +28 -10
  67. package/dist/activities/workflow-event-activities.js +87 -58
  68. package/dist/activities/workflow-event-activities.js.map +1 -1
  69. package/dist/claimcheck/payload-codec.js +21 -1
  70. package/dist/claimcheck/payload-codec.js.map +1 -1
  71. package/dist/client/stigmer-client.d.ts +9 -4
  72. package/dist/client/stigmer-client.js +28 -15
  73. package/dist/client/stigmer-client.js.map +1 -1
  74. package/dist/encryption/config.d.ts +32 -0
  75. package/dist/encryption/config.js +68 -0
  76. package/dist/encryption/config.js.map +1 -0
  77. package/dist/encryption/index.d.ts +3 -0
  78. package/dist/encryption/index.js +3 -0
  79. package/dist/encryption/index.js.map +1 -0
  80. package/dist/encryption/payload-codec.d.ts +41 -0
  81. package/dist/encryption/payload-codec.js +130 -0
  82. package/dist/encryption/payload-codec.js.map +1 -0
  83. package/dist/payload-codecs.d.ts +16 -0
  84. package/dist/payload-codecs.js +38 -0
  85. package/dist/payload-codecs.js.map +1 -0
  86. package/dist/preflight.d.ts +31 -0
  87. package/dist/preflight.js +43 -0
  88. package/dist/preflight.js.map +1 -1
  89. package/dist/runner-manager.js +5 -15
  90. package/dist/runner-manager.js.map +1 -1
  91. package/dist/runner.js +5 -16
  92. package/dist/runner.js.map +1 -1
  93. package/dist/shared/approval-policy.d.ts +9 -3
  94. package/dist/shared/approval-policy.js +15 -6
  95. package/dist/shared/approval-policy.js.map +1 -1
  96. package/dist/shared/attachment-naming.d.ts +53 -0
  97. package/dist/shared/attachment-naming.js +59 -0
  98. package/dist/shared/attachment-naming.js.map +1 -0
  99. package/dist/shared/attachment-vision.d.ts +43 -2
  100. package/dist/shared/attachment-vision.js +72 -6
  101. package/dist/shared/attachment-vision.js.map +1 -1
  102. package/dist/shared/caller-identity.d.ts +23 -2
  103. package/dist/shared/caller-identity.js +36 -5
  104. package/dist/shared/caller-identity.js.map +1 -1
  105. package/dist/shared/channel-attachment.js +1 -0
  106. package/dist/shared/channel-attachment.js.map +1 -1
  107. package/dist/shared/checkpointer/http-saver.d.ts +42 -1
  108. package/dist/shared/checkpointer/http-saver.js +96 -8
  109. package/dist/shared/checkpointer/http-saver.js.map +1 -1
  110. package/dist/shared/conversation-attachment.js +1 -0
  111. package/dist/shared/conversation-attachment.js.map +1 -1
  112. package/dist/shared/datastore-attachment.d.ts +50 -7
  113. package/dist/shared/datastore-attachment.js +93 -11
  114. package/dist/shared/datastore-attachment.js.map +1 -1
  115. package/dist/shared/http-retry.d.ts +43 -0
  116. package/dist/shared/http-retry.js +50 -0
  117. package/dist/shared/http-retry.js.map +1 -0
  118. package/dist/shared/llm-backend.d.ts +275 -0
  119. package/dist/shared/llm-backend.js +425 -0
  120. package/dist/shared/llm-backend.js.map +1 -0
  121. package/dist/shared/llm-proxy.d.ts +8 -0
  122. package/dist/shared/llm-proxy.js +15 -0
  123. package/dist/shared/llm-proxy.js.map +1 -1
  124. package/dist/shared/mcp-enabled-tools.d.ts +57 -0
  125. package/dist/shared/mcp-enabled-tools.js +86 -0
  126. package/dist/shared/mcp-enabled-tools.js.map +1 -0
  127. package/dist/shared/mcp-manager.d.ts +17 -2
  128. package/dist/shared/mcp-manager.js +37 -25
  129. package/dist/shared/mcp-manager.js.map +1 -1
  130. package/dist/shared/mcp-resolver.d.ts +39 -2
  131. package/dist/shared/mcp-resolver.js +38 -2
  132. package/dist/shared/mcp-resolver.js.map +1 -1
  133. package/dist/shared/model-client.d.ts +12 -5
  134. package/dist/shared/model-client.js +138 -18
  135. package/dist/shared/model-client.js.map +1 -1
  136. package/dist/shared/model-error.js +198 -5
  137. package/dist/shared/model-error.js.map +1 -1
  138. package/dist/shared/model-registry.d.ts +20 -2
  139. package/dist/shared/model-registry.js +37 -2
  140. package/dist/shared/model-registry.js.map +1 -1
  141. package/dist/shared/plan-mode-permissions.d.ts +26 -0
  142. package/dist/shared/plan-mode-permissions.js +28 -0
  143. package/dist/shared/plan-mode-permissions.js.map +1 -0
  144. package/dist/worker.d.ts +2 -1
  145. package/dist/worker.js +2 -4
  146. package/dist/worker.js.map +1 -1
  147. package/dist/workflow-engine/types.d.ts +18 -0
  148. package/dist/workflow-engine/types.js.map +1 -1
  149. package/dist/workflows/call-agent-orchestrator.d.ts +9 -0
  150. package/dist/workflows/call-agent-orchestrator.js +1 -0
  151. package/dist/workflows/call-agent-orchestrator.js.map +1 -1
  152. package/dist/workflows/connect-mcp-server.js +7 -0
  153. package/dist/workflows/connect-mcp-server.js.map +1 -1
  154. package/dist/workflows/engine-core.js +23 -2
  155. package/dist/workflows/engine-core.js.map +1 -1
  156. package/dist/workflows/execute-from-execution.d.ts +1 -1
  157. package/dist/workflows/execute-from-execution.js +11 -1
  158. package/dist/workflows/execute-from-execution.js.map +1 -1
  159. package/package.json +8 -2
  160. package/src/__tests__/claimcheck-codec.test.ts +36 -0
  161. package/src/__tests__/encryption-codec.test.ts +234 -0
  162. package/src/__tests__/fixtures/encrypted-payload-fixture.json +15 -0
  163. package/src/__tests__/history-encryption-e2e.test.ts +243 -0
  164. package/src/__tests__/preflight.test.ts +50 -2
  165. package/src/activities/__tests__/call-llm.test.ts +75 -0
  166. package/src/activities/__tests__/classify-tool-approvals.test.ts +117 -1
  167. package/src/activities/__tests__/discover-mcp-server.hang.test.ts +103 -0
  168. package/src/activities/__tests__/discover-mcp-server.test.ts +203 -0
  169. package/src/activities/__tests__/workflow-event-activities.test.ts +107 -8
  170. package/src/activities/call-llm.ts +9 -16
  171. package/src/activities/classify-tool-approvals.ts +34 -4
  172. package/src/activities/discover-mcp-server.ts +190 -32
  173. package/src/activities/execute-cursor/__test-utils__/cursor-hook-harness.ts +9 -0
  174. package/src/activities/execute-cursor/__tests__/approval-gate.test.ts +14 -0
  175. package/src/activities/execute-cursor/__tests__/attachment-resolver.test.ts +92 -0
  176. package/src/activities/execute-cursor/__tests__/build-prompt.test.ts +40 -14
  177. package/src/activities/execute-cursor/__tests__/error-classifier-extraction.test.ts +208 -0
  178. package/src/activities/execute-cursor/__tests__/extract-structured-output.test.ts +120 -0
  179. package/src/activities/execute-cursor/__tests__/hook-script.test.ts +93 -0
  180. package/src/activities/execute-cursor/__tests__/mcp-resolver.test.ts +125 -0
  181. package/src/activities/execute-cursor/__tests__/prompt-builder-delegation.test.ts +1 -1
  182. package/src/activities/execute-cursor/__tests__/turn-stream.test.ts +13 -0
  183. package/src/activities/execute-cursor/approval-state.ts +30 -1
  184. package/src/activities/execute-cursor/attachment-resolver.ts +38 -3
  185. package/src/activities/execute-cursor/blueprint-resolver.ts +7 -27
  186. package/src/activities/execute-cursor/env-resolver.ts +3 -1
  187. package/src/activities/execute-cursor/error-classifier.ts +91 -4
  188. package/src/activities/execute-cursor/extract-structured-output.ts +72 -0
  189. package/src/activities/execute-cursor/hook-script.ts +74 -10
  190. package/src/activities/execute-cursor/index.ts +63 -72
  191. package/src/activities/execute-cursor/mcp-resolver.ts +36 -2
  192. package/src/activities/execute-cursor/prompt-builder.ts +34 -9
  193. package/src/activities/execute-cursor/turn-stream.ts +5 -2
  194. package/src/activities/execute-deep-agent/__tests__/attachment-injector.test.ts +132 -8
  195. package/src/activities/execute-deep-agent/__tests__/datastore-degradation.test.ts +104 -0
  196. package/src/activities/execute-deep-agent/__tests__/hitl-reject.test.ts +2 -0
  197. package/src/activities/execute-deep-agent/__tests__/hitl-resume-approve-all.test.ts +1 -0
  198. package/src/activities/execute-deep-agent/__tests__/hitl-resume-history.test.ts +1 -0
  199. package/src/activities/execute-deep-agent/__tests__/prompt-builder.test.ts +34 -5
  200. package/src/activities/execute-deep-agent/__tests__/sequential-gate-resume.test.ts +1 -0
  201. package/src/activities/execute-deep-agent/__tests__/subagent-plan-mode-permissions.test.ts +173 -0
  202. package/src/activities/execute-deep-agent/__tests__/subagent-wiring.test.ts +12 -7
  203. package/src/activities/execute-deep-agent/attachment-injector.ts +94 -30
  204. package/src/activities/execute-deep-agent/environment.ts +3 -1
  205. package/src/activities/execute-deep-agent/index.ts +20 -0
  206. package/src/activities/execute-deep-agent/prompt-builder.ts +20 -10
  207. package/src/activities/execute-deep-agent/setup.ts +86 -31
  208. package/src/activities/execute-deep-agent/subagent-transformer.ts +23 -1
  209. package/src/activities/execute-deep-agent/subagent-wiring.ts +14 -4
  210. package/src/activities/hydrate-workflow-execution.ts +3 -1
  211. package/src/activities/workflow-event-activities.ts +96 -69
  212. package/src/claimcheck/payload-codec.ts +33 -1
  213. package/src/client/__tests__/stigmer-client.test.ts +8 -8
  214. package/src/client/stigmer-client.ts +32 -18
  215. package/src/encryption/config.ts +91 -0
  216. package/src/encryption/index.ts +3 -0
  217. package/src/encryption/payload-codec.ts +152 -0
  218. package/src/payload-codecs.ts +56 -0
  219. package/src/preflight.ts +45 -0
  220. package/src/runner-manager.ts +6 -24
  221. package/src/runner.ts +6 -25
  222. package/src/shared/__tests__/approval-policy.test.ts +82 -39
  223. package/src/shared/__tests__/attachment-naming.test.ts +159 -0
  224. package/src/shared/__tests__/attachment-vision.test.ts +97 -0
  225. package/src/shared/__tests__/bedrock-adapter.test.ts +213 -0
  226. package/src/shared/__tests__/bedrock-seam.test.ts +390 -0
  227. package/src/shared/__tests__/caller-identity.test.ts +25 -0
  228. package/src/shared/__tests__/channel-attachment.test.ts +1 -1
  229. package/src/shared/__tests__/connect-backfill.test.ts +1 -0
  230. package/src/shared/__tests__/conversation-attachment.test.ts +1 -1
  231. package/src/shared/__tests__/datastore-attachment.test.ts +129 -1
  232. package/src/shared/__tests__/foundry-adapter.test.ts +276 -0
  233. package/src/shared/__tests__/foundry-seam.test.ts +482 -0
  234. package/src/shared/__tests__/http-retry.test.ts +67 -0
  235. package/src/shared/__tests__/llm-backend.test.ts +616 -0
  236. package/src/shared/__tests__/mcp-enabled-tools.test.ts +86 -0
  237. package/src/shared/__tests__/mcp-manager.test.ts +170 -2
  238. package/src/shared/__tests__/mcp-resolver.test.ts +146 -3
  239. package/src/shared/__tests__/model-client.test.ts +154 -0
  240. package/src/shared/__tests__/model-error.test.ts +289 -1
  241. package/src/shared/__tests__/model-registry.test.ts +71 -0
  242. package/src/shared/__tests__/synthesized-attachment.test.ts +1 -0
  243. package/src/shared/__tests__/vertex-adapter.test.ts +169 -0
  244. package/src/shared/__tests__/vertex-seam.test.ts +295 -0
  245. package/src/shared/approval-policy.ts +14 -7
  246. package/src/shared/attachment-naming.ts +78 -0
  247. package/src/shared/attachment-vision.ts +92 -9
  248. package/src/shared/caller-identity.ts +40 -5
  249. package/src/shared/channel-attachment.ts +1 -0
  250. package/src/shared/checkpointer/__tests__/http-saver.test.ts +196 -1
  251. package/src/shared/checkpointer/http-saver.ts +117 -9
  252. package/src/shared/conversation-attachment.ts +1 -0
  253. package/src/shared/datastore-attachment.ts +106 -11
  254. package/src/shared/http-retry.ts +50 -0
  255. package/src/shared/llm-backend.ts +544 -0
  256. package/src/shared/llm-proxy.ts +15 -0
  257. package/src/shared/mcp-enabled-tools.ts +105 -0
  258. package/src/shared/mcp-manager.ts +43 -26
  259. package/src/shared/mcp-resolver.ts +73 -2
  260. package/src/shared/model-client.ts +161 -19
  261. package/src/shared/model-error.ts +222 -4
  262. package/src/shared/model-registry.ts +50 -2
  263. package/src/shared/plan-mode-permissions.ts +30 -0
  264. package/src/worker.ts +4 -5
  265. package/src/workflow-engine/types.ts +18 -0
  266. package/src/workflows/__tests__/execute-serverless-workflow.test.ts +68 -2
  267. package/src/workflows/call-agent-orchestrator.ts +10 -0
  268. package/src/workflows/connect-mcp-server.ts +7 -0
  269. package/src/workflows/engine-core.ts +23 -2
  270. package/src/workflows/execute-from-execution.ts +12 -2
@@ -0,0 +1,544 @@
1
+ /**
2
+ * LLM provider-backend utilities — pure routing helpers for serving a
3
+ * provider's models through an alternative cloud backend (GCP Vertex AI,
4
+ * AWS Bedrock, Microsoft Foundry) instead of the provider's public API.
5
+ *
6
+ * Layering mirrors `llm-proxy.ts`: this module is pure string/config
7
+ * utilities with no LangChain or SDK dependency. Consumers: the runner
8
+ * factories run `preflightLlmBackends` at startup, and `model-client.ts`
9
+ * resolves the backend and translates model ids at construction time; see
10
+ * `__tests__/vertex-seam.test.ts` for the pinned seam behavior.
11
+ *
12
+ * Design decision record: stigmer-cloud
13
+ * `_projects/2026-08/20260809.01.multi-cloud-llm-provider-endpoints/`
14
+ * `design-decisions/001-provider-backends.md`.
15
+ */
16
+
17
+ import type { LlmProvider } from "./llm-proxy.js";
18
+
19
+ // ─── Backend selection ───────────────────────────────────────────────────────
20
+
21
+ /** Env var selecting where Anthropic models are served. */
22
+ export const ANTHROPIC_BACKEND_ENV = "STIGMER_ANTHROPIC_BACKEND";
23
+ /** Env var selecting where OpenAI models are served. */
24
+ export const OPENAI_BACKEND_ENV = "STIGMER_OPENAI_BACKEND";
25
+
26
+ /** Operator guide for backend configuration; the single copy of this URL. */
27
+ export const BACKEND_DOC_URL = "https://docs.stigmer.ai/guides/runners/model-backends";
28
+
29
+ /**
30
+ * Backends implemented in this build. Anthropic's values name the serving
31
+ * SERVICE, not the cloud (`foundry` is Microsoft Foundry, the Azure
32
+ * service that hosts Claude — "azure" would collide with the unrelated
33
+ * Azure OpenAI service). The design vocabulary also reserves `azure`
34
+ * (OpenAI); until that adapter lands — contingent on OpenAI models
35
+ * entering the native catalog — selecting it is a distinct "recognized
36
+ * but not implemented" failure, never a silent fallback to the public
37
+ * API, which would quietly route traffic outside the compliance boundary
38
+ * the operator asked for.
39
+ */
40
+ export type AnthropicBackend = "public" | "vertex" | "bedrock" | "foundry";
41
+ export type OpenAiBackend = "public";
42
+
43
+ /**
44
+ * Result of parsing a backend env var. `message` is the operator-facing
45
+ * text; it names the exact var, the bad value, and what is supported, and
46
+ * is the single copy of that text (preflight, model construction, and any
47
+ * future consumer all surface this same string).
48
+ */
49
+ export type BackendParseResult<B> =
50
+ | { readonly ok: true; readonly backend: B }
51
+ | { readonly ok: false; readonly message: string };
52
+
53
+ /** Planned-but-unshipped values get a "not in this build" message. */
54
+ const PLANNED_ANTHROPIC: string[] = [];
55
+ const PLANNED_OPENAI = ["azure"];
56
+
57
+ function parseBackend<B extends string>(
58
+ envVar: string,
59
+ raw: string | undefined,
60
+ supported: readonly B[],
61
+ planned: readonly string[],
62
+ ): BackendParseResult<B> {
63
+ const value = raw?.trim().toLowerCase() ?? "";
64
+ if (value === "") {
65
+ // Unset means the provider's public API — the zero-config default.
66
+ return { ok: true, backend: "public" as B };
67
+ }
68
+ if ((supported as readonly string[]).includes(value)) {
69
+ return { ok: true, backend: value as B };
70
+ }
71
+ if (planned.includes(value)) {
72
+ return {
73
+ ok: false,
74
+ message:
75
+ `${envVar}="${value}" is not implemented in this build yet. ` +
76
+ `Supported today: ${supported.join(", ")}. See ${BACKEND_DOC_URL}.`,
77
+ };
78
+ }
79
+ return {
80
+ ok: false,
81
+ message:
82
+ `${envVar}="${raw?.trim()}" is not a supported backend. ` +
83
+ `Supported: ${supported.join(", ")}. See ${BACKEND_DOC_URL}.`,
84
+ };
85
+ }
86
+
87
+ /** Parse `STIGMER_ANTHROPIC_BACKEND` (unset → `public`). */
88
+ export function parseAnthropicBackend(
89
+ env: NodeJS.ProcessEnv = process.env,
90
+ ): BackendParseResult<AnthropicBackend> {
91
+ return parseBackend(
92
+ ANTHROPIC_BACKEND_ENV,
93
+ env[ANTHROPIC_BACKEND_ENV],
94
+ ["public", "vertex", "bedrock", "foundry"],
95
+ PLANNED_ANTHROPIC,
96
+ );
97
+ }
98
+
99
+ /** Parse `STIGMER_OPENAI_BACKEND` (unset → `public`). */
100
+ export function parseOpenAiBackend(
101
+ env: NodeJS.ProcessEnv = process.env,
102
+ ): BackendParseResult<OpenAiBackend> {
103
+ return parseBackend(
104
+ OPENAI_BACKEND_ENV,
105
+ env[OPENAI_BACKEND_ENV],
106
+ ["public"],
107
+ // `vertex`/`bedrock` under the OpenAI var are wrong-provider values, not
108
+ // planned ones — they fall through to the unsupported-value message.
109
+ PLANNED_OPENAI,
110
+ );
111
+ }
112
+
113
+ /**
114
+ * Resolve the Anthropic backend for model construction, throwing the
115
+ * parser's message on an invalid value.
116
+ *
117
+ * The runner factories run {@link preflightLlmBackends} at startup, so in a
118
+ * normally-booted process this never throws — the throw is defense in depth
119
+ * for paths that construct models without the factories (tests, direct
120
+ * library use), keeping "invalid value" impossible to ride past silently.
121
+ */
122
+ export function resolveAnthropicBackend(
123
+ env: NodeJS.ProcessEnv = process.env,
124
+ ): AnthropicBackend {
125
+ const parsed = parseAnthropicBackend(env);
126
+ if (!parsed.ok) throw new Error(parsed.message);
127
+ return parsed.backend;
128
+ }
129
+
130
+ /**
131
+ * Static prerequisite check for the vertex backend, or null when satisfied.
132
+ *
133
+ * Region is the ONE hard requirement checkable without I/O: the Vertex SDK
134
+ * throws without it. Project id and credentials are deliberately NOT
135
+ * checked here — both are legitimately resolvable at request time from
136
+ * Application Default Credentials (workload identity, metadata server,
137
+ * gcloud login), so requiring env vars for them would reject perfectly
138
+ * valid GCP deployments. Runtime credential failures get actionable
139
+ * classification in `model-error.ts` instead.
140
+ */
141
+ export function checkVertexPrerequisites(
142
+ env: NodeJS.ProcessEnv = process.env,
143
+ ): string | null {
144
+ if (env.CLOUD_ML_REGION?.trim()) return null;
145
+ return (
146
+ `The vertex backend requires CLOUD_ML_REGION (e.g. "asia-south1", or ` +
147
+ `"global" for the global endpoint). See ${BACKEND_DOC_URL}.`
148
+ );
149
+ }
150
+
151
+ /** Operator override map: canonical id -> exact Bedrock id, consulted first. */
152
+ export const BEDROCK_MODEL_MAP_ENV = "STIGMER_BEDROCK_MODEL_MAP";
153
+ /** Inference-profile geography prefix (`us`, `eu`, `global`, …), no default. */
154
+ export const BEDROCK_INFERENCE_PREFIX_ENV = "STIGMER_BEDROCK_INFERENCE_PREFIX";
155
+
156
+ /**
157
+ * Static prerequisite check for the bedrock backend, or null when satisfied.
158
+ *
159
+ * AWS_REGION is REQUIRED even though the Bedrock SDK would default it to
160
+ * us-east-1 (pinned by bedrock-seam.test.ts): for a deployment-controlled
161
+ * data-residency feature, silently routing model traffic to a US region on
162
+ * a missing var is exactly the failure backends exist to prevent. Same
163
+ * shape as vertex's CLOUD_ML_REGION requirement. Credentials are
164
+ * deliberately NOT checked — the AWS chain (env keys, IRSA / instance
165
+ * metadata, config files, AWS_BEARER_TOKEN_BEDROCK) legitimately resolves
166
+ * at request time; requiring env keys would reject valid deployments.
167
+ * Runtime credential failures get actionable classification in
168
+ * `model-error.ts` instead.
169
+ *
170
+ * A malformed STIGMER_BEDROCK_MODEL_MAP is also fatal here: it is
171
+ * deployment-static, and finding out at the first model call would fail
172
+ * executions a boot check could have refused.
173
+ */
174
+ export function checkBedrockPrerequisites(
175
+ env: NodeJS.ProcessEnv = process.env,
176
+ ): string | null {
177
+ if (!env.AWS_REGION?.trim()) {
178
+ return (
179
+ `The bedrock backend requires AWS_REGION (e.g. "ap-south-1"). It is ` +
180
+ `required even though the AWS SDK would default to us-east-1 — a ` +
181
+ `deployment that chose Bedrock for data residency must never fall ` +
182
+ `back to another region silently. See ${BACKEND_DOC_URL}.`
183
+ );
184
+ }
185
+ const map = parseBedrockModelMap(env);
186
+ if (!map.ok) return map.message;
187
+ return null;
188
+ }
189
+
190
+ type ModelMapParseResult =
191
+ | { readonly ok: true; readonly map: ReadonlyMap<string, string> }
192
+ | { readonly ok: false; readonly message: string };
193
+
194
+ /**
195
+ * Shared parser for the per-backend override maps: comma-separated
196
+ * `canonical=target` pairs. Unset or blank parses to an empty map (the
197
+ * backend's deterministic rule serves every model). Each env var keeps its
198
+ * own single copy of the malformed-entry text through `form`/`example` —
199
+ * preflight and translation surface the same string.
200
+ */
201
+ function parseModelMap(
202
+ envVar: string,
203
+ raw: string | undefined,
204
+ form: string,
205
+ example: string,
206
+ ): ModelMapParseResult {
207
+ const trimmed = raw?.trim();
208
+ const map = new Map<string, string>();
209
+ if (!trimmed) return { ok: true, map };
210
+
211
+ for (const entry of trimmed.split(",")) {
212
+ const pair = entry.trim();
213
+ if (pair === "") continue;
214
+ const eq = pair.indexOf("=");
215
+ const canonical = eq === -1 ? "" : pair.slice(0, eq).trim();
216
+ const target = eq === -1 ? "" : pair.slice(eq + 1).trim();
217
+ if (!canonical || !target) {
218
+ return {
219
+ ok: false,
220
+ message:
221
+ `${envVar} entry "${pair}" is not of the form ${form} ` +
222
+ `(e.g. "${example}"). Entries are comma-separated. ` +
223
+ `See ${BACKEND_DOC_URL}.`,
224
+ };
225
+ }
226
+ map.set(canonical, target);
227
+ }
228
+ return { ok: true, map };
229
+ }
230
+
231
+ /**
232
+ * Parse `STIGMER_BEDROCK_MODEL_MAP`: comma-separated `canonical=bedrockId`
233
+ * pairs, e.g. "claude-sonnet-4-6=us.anthropic.claude-sonnet-4-6-v1:0".
234
+ */
235
+ export function parseBedrockModelMap(
236
+ env: NodeJS.ProcessEnv = process.env,
237
+ ): ModelMapParseResult {
238
+ return parseModelMap(
239
+ BEDROCK_MODEL_MAP_ENV,
240
+ env[BEDROCK_MODEL_MAP_ENV],
241
+ "canonical=bedrockId",
242
+ "claude-sonnet-4-6=us.anthropic.claude-sonnet-4-6-v1:0",
243
+ );
244
+ }
245
+
246
+ // ─── Microsoft Foundry (Azure) ───────────────────────────────────────────────
247
+
248
+ /**
249
+ * Operator override map: canonical id -> Foundry deployment name, consulted
250
+ * first. Named DEPLOYMENT_MAP, not MODEL_MAP, because the target is Azure's
251
+ * term of art — the operator-chosen deployment name, not another model id.
252
+ */
253
+ export const FOUNDRY_DEPLOYMENT_MAP_ENV = "STIGMER_FOUNDRY_DEPLOYMENT_MAP";
254
+ /** The Foundry resource name (SDK-native; builds the endpoint host). */
255
+ export const FOUNDRY_RESOURCE_ENV = "ANTHROPIC_FOUNDRY_RESOURCE";
256
+ /** Full endpoint override (SDK-native; mutually exclusive with resource). */
257
+ export const FOUNDRY_BASE_URL_ENV = "ANTHROPIC_FOUNDRY_BASE_URL";
258
+
259
+ /**
260
+ * Parse `STIGMER_FOUNDRY_DEPLOYMENT_MAP`: comma-separated
261
+ * `canonical=deploymentName` pairs, e.g.
262
+ * "claude-sonnet-4-6=my-sonnet-deployment".
263
+ */
264
+ export function parseFoundryDeploymentMap(
265
+ env: NodeJS.ProcessEnv = process.env,
266
+ ): ModelMapParseResult {
267
+ return parseModelMap(
268
+ FOUNDRY_DEPLOYMENT_MAP_ENV,
269
+ env[FOUNDRY_DEPLOYMENT_MAP_ENV],
270
+ "canonical=deploymentName",
271
+ "claude-sonnet-4-6=my-sonnet-deployment",
272
+ );
273
+ }
274
+
275
+ /**
276
+ * Static prerequisite check for the foundry backend, or null when satisfied.
277
+ *
278
+ * The endpoint is the ONE hard requirement checkable without I/O: the
279
+ * Foundry SDK's constructor throws without exactly one of the resource
280
+ * name or a full base URL, so both halves of its contract (missing AND
281
+ * both-set) are refused here at boot with catalog messages instead of at
282
+ * the first model call. Credentials are deliberately NOT checked —
283
+ * ANTHROPIC_FOUNDRY_API_KEY is optional by design (without it the adapter
284
+ * authenticates through Microsoft Entra ID via the Azure credential chain,
285
+ * which resolves at request time exactly like Vertex ADC and the AWS
286
+ * chain), so requiring it would reject correctly-configured keyless
287
+ * deployments. Runtime credential failures get actionable classification
288
+ * in `model-error.ts` instead.
289
+ *
290
+ * A malformed STIGMER_FOUNDRY_DEPLOYMENT_MAP is also fatal here: it is
291
+ * deployment-static, and finding out at the first model call would fail
292
+ * executions a boot check could have refused.
293
+ */
294
+ export function checkFoundryPrerequisites(
295
+ env: NodeJS.ProcessEnv = process.env,
296
+ ): string | null {
297
+ const resource = env[FOUNDRY_RESOURCE_ENV]?.trim();
298
+ const baseUrl = env[FOUNDRY_BASE_URL_ENV]?.trim();
299
+ if (!resource && !baseUrl) {
300
+ return (
301
+ `The foundry backend requires ${FOUNDRY_RESOURCE_ENV} (your Microsoft ` +
302
+ `Foundry resource name, e.g. "my-foundry-resource") or ` +
303
+ `${FOUNDRY_BASE_URL_ENV} (the full endpoint, e.g. ` +
304
+ `"https://my-foundry-resource.services.ai.azure.com/anthropic/"). ` +
305
+ `See ${BACKEND_DOC_URL}.`
306
+ );
307
+ }
308
+ if (resource && baseUrl) {
309
+ return (
310
+ `${FOUNDRY_RESOURCE_ENV} and ${FOUNDRY_BASE_URL_ENV} are mutually ` +
311
+ `exclusive — the base URL is derived from the resource name. Set ` +
312
+ `exactly one. See ${BACKEND_DOC_URL}.`
313
+ );
314
+ }
315
+ const map = parseFoundryDeploymentMap(env);
316
+ if (!map.ok) return map.message;
317
+ return null;
318
+ }
319
+
320
+ /**
321
+ * Check that direct-mode (unproxied) calls to `provider` have a usable
322
+ * credential path, or return the operator message describing what is
323
+ * missing. Null means "a request can authenticate":
324
+ *
325
+ * - `anthropic`: a non-blank `ANTHROPIC_API_KEY`, or any non-public backend
326
+ * (vertex authenticates through Application Default Credentials, and
327
+ * `ChatAnthropic` waives its API-key requirement when `createClient` is
328
+ * supplied — pinned by vertex-seam.test.ts).
329
+ * - `openai`: a non-blank `OPENAI_API_KEY`. The message deliberately offers
330
+ * no backend remedy until the azure adapter ships — advertising
331
+ * STIGMER_OPENAI_BACKEND today would point the operator at a value that
332
+ * fails with "not implemented in this build".
333
+ *
334
+ * An invalid backend value also returns null: `resolveAnthropicBackend` at
335
+ * model construction owns that condition's precise catalog message, and
336
+ * reporting it here too would create a second copy that can drift.
337
+ *
338
+ * This is the single copy of the "do we have a credential?" question. The
339
+ * reaction stays with each caller, because the right one differs per site:
340
+ * `call-llm.ts` raises a non-retryable LLM_MISSING_API_KEY, tool
341
+ * classification fails closed (every tool gated), and Cursor tier-2
342
+ * extraction skips to "no structured output". Callers consult it only when
343
+ * no proxy is configured — a proxied deployment authenticates with
344
+ * STIGMER_TOKEN and holds no provider credentials at all.
345
+ */
346
+ export function checkDirectCredentials(
347
+ provider: LlmProvider,
348
+ env: NodeJS.ProcessEnv = process.env,
349
+ ): string | null {
350
+ if (provider === "openai") {
351
+ if (env.OPENAI_API_KEY?.trim()) return null;
352
+ return (
353
+ `OPENAI_API_KEY is not set and no proxy is configured. Set the API ` +
354
+ `key in your environment or connect to a Stigmer Cloud deployment. ` +
355
+ `See ${BACKEND_DOC_URL}.`
356
+ );
357
+ }
358
+ if (env.ANTHROPIC_API_KEY?.trim()) return null;
359
+ const parsed = parseAnthropicBackend(env);
360
+ if (!parsed.ok || parsed.backend !== "public") return null;
361
+ return (
362
+ `ANTHROPIC_API_KEY is not set, no model backend is configured, and no ` +
363
+ `proxy is configured. Set the API key, configure a backend (e.g. ` +
364
+ `${ANTHROPIC_BACKEND_ENV}=vertex, bedrock, or foundry), or connect to ` +
365
+ `a Stigmer Cloud deployment. See ${BACKEND_DOC_URL}.`
366
+ );
367
+ }
368
+
369
+ export interface LlmBackendPreflight {
370
+ /** Fatal, actionable operator message; null when the config is usable. */
371
+ readonly error: string | null;
372
+ /** Non-fatal operator notices (e.g. proxy overrides backend selection). */
373
+ readonly warnings: readonly string[];
374
+ }
375
+
376
+ /**
377
+ * Validate the deployment's backend configuration once, at startup.
378
+ *
379
+ * Called by the runner factories (`createStigmerRunner` /
380
+ * `createStigmerRunnerManager`) — the construction boundary every entry
381
+ * path shares (static, pool, and manager modes in main.ts, plus in-process
382
+ * embedders of `@stigmer/runner`) — so a misconfigured deployment refuses
383
+ * to accept work instead of failing every execution mid-flight. Mirrors the
384
+ * `preflightNodeRuntime` pattern: pure check in, operator message out.
385
+ *
386
+ * Precedence rule: when `STIGMER_PROXY_ENDPOINT` is set the proxy owns
387
+ * provider routing and backend vars are inert, so they downgrade to
388
+ * warnings (never silence, but never fail a proxied fleet over an ignored
389
+ * var either). Without a proxy, invalid values and missing prerequisites
390
+ * are fatal.
391
+ */
392
+ export function preflightLlmBackends(
393
+ env: NodeJS.ProcessEnv = process.env,
394
+ ): LlmBackendPreflight {
395
+ const proxySet = !!env.STIGMER_PROXY_ENDPOINT?.trim();
396
+
397
+ if (proxySet) {
398
+ const warnings: string[] = [];
399
+ for (const envVar of [ANTHROPIC_BACKEND_ENV, OPENAI_BACKEND_ENV]) {
400
+ const raw = env[envVar]?.trim();
401
+ if (raw && raw.toLowerCase() !== "public") {
402
+ warnings.push(
403
+ `STIGMER_PROXY_ENDPOINT is set; ${envVar}=${raw} is ignored — ` +
404
+ `the proxy owns provider routing.`,
405
+ );
406
+ }
407
+ }
408
+ return { error: null, warnings };
409
+ }
410
+
411
+ const errors: string[] = [];
412
+ const anthropic = parseAnthropicBackend(env);
413
+ if (!anthropic.ok) {
414
+ errors.push(anthropic.message);
415
+ } else if (anthropic.backend === "vertex") {
416
+ const prereq = checkVertexPrerequisites(env);
417
+ if (prereq !== null) errors.push(prereq);
418
+ } else if (anthropic.backend === "bedrock") {
419
+ const prereq = checkBedrockPrerequisites(env);
420
+ if (prereq !== null) errors.push(prereq);
421
+ } else if (anthropic.backend === "foundry") {
422
+ const prereq = checkFoundryPrerequisites(env);
423
+ if (prereq !== null) errors.push(prereq);
424
+ }
425
+ const openai = parseOpenAiBackend(env);
426
+ if (!openai.ok) errors.push(openai.message);
427
+
428
+ return { error: errors.length > 0 ? errors.join("\n") : null, warnings: [] };
429
+ }
430
+
431
+ // ─── Model-id translation ────────────────────────────────────────────────────
432
+
433
+ /**
434
+ * Matches a registry `apiModelId` that ends in a pre-4.6 snapshot date
435
+ * (`-YYYYMMDD`), e.g. "claude-sonnet-4-5-20250929".
436
+ */
437
+ const TRAILING_SNAPSHOT_DATE = /-(\d{8})$/;
438
+
439
+ /**
440
+ * Translate a canonical Anthropic API model id into Vertex AI's form.
441
+ *
442
+ * The model registry serves two id shapes, and Vertex treats them
443
+ * differently (platform.claude.com "Model IDs and versions"):
444
+ *
445
+ * - Pre-4.6 models carry a snapshot date, and Vertex separates it with `@`
446
+ * instead of `-`: "claude-sonnet-4-5-20250929" -> "claude-sonnet-4-5@20250929".
447
+ * - 4.6-generation and later ids are dateless AND canonical on every
448
+ * platform: "claude-sonnet-4-6" is used verbatim on Vertex. Appending a
449
+ * date to them 404s — a real bug shipped by other integrations (Dify
450
+ * langgenius/dify-official-plugins#2905, Roo-Code #11625) — so dateless
451
+ * ids MUST pass through untouched.
452
+ *
453
+ * The translated id is Vertex wire detail only: it goes into the request
454
+ * URL path and must never escape the adapter into usage metrics or pricing,
455
+ * which key on the canonical id (the canonical-id invariant in the design
456
+ * decision record).
457
+ *
458
+ * Already-translated ids (`name@date`) and Bedrock-shaped ids
459
+ * (`anthropic.…-v1:0`) don't match the trailing-date pattern, so a second
460
+ * pass is a no-op by construction.
461
+ */
462
+ export function toVertexModelId(apiModelId: string): string {
463
+ return apiModelId.replace(TRAILING_SNAPSHOT_DATE, "@$1");
464
+ }
465
+
466
+ /**
467
+ * Translate a canonical Anthropic API model id into Bedrock's form, in
468
+ * three layers (approved design, T04) — each a deployment-level knob:
469
+ *
470
+ * 1. `STIGMER_BEDROCK_MODEL_MAP` override, consulted first: the escape
471
+ * hatch for ids the deterministic rule cannot derive (Bedrock ids for
472
+ * dateless canonicals may carry AWS-side snapshot dates we cannot know).
473
+ * 2. `STIGMER_BEDROCK_INFERENCE_PREFIX` (e.g. "us", "eu", "global"),
474
+ * applied to the derived id. Newer Claude models on Bedrock are invoked
475
+ * through geography-prefixed inference profiles (AWS lists the base id's
476
+ * in-region endpoint as N/A) — but WHICH geography is a deployment
477
+ * decision (data residency), underivable from the model id, and never
478
+ * defaulted: a missing prefix yields the bare id, and if AWS rejects it
479
+ * with its "use an inference profile" error, model-error.ts translates
480
+ * that into "set ${BEDROCK_INFERENCE_PREFIX_ENV}".
481
+ * 3. Deterministic rule: `anthropic.{canonical}-v1:0` — verified against
482
+ * AWS's model catalog for the registry's dated ids (e.g.
483
+ * claude-sonnet-4-5-20250929 -> anthropic.claude-sonnet-4-5-20250929-v1:0).
484
+ *
485
+ * Like the Vertex translation, the result is wire detail only: it rides in
486
+ * the request URL and must never escape the adapter into usage metrics or
487
+ * pricing, which key on the canonical id (the canonical-id invariant).
488
+ *
489
+ * Throws the catalog message on a malformed map — defense in depth for
490
+ * paths that construct models without the factories; a normally-booted
491
+ * runner already refused to start in `checkBedrockPrerequisites`.
492
+ */
493
+ export function toBedrockModelId(
494
+ apiModelId: string,
495
+ env: NodeJS.ProcessEnv = process.env,
496
+ ): string {
497
+ const parsed = parseBedrockModelMap(env);
498
+ if (!parsed.ok) throw new Error(parsed.message);
499
+ const mapped = parsed.map.get(apiModelId);
500
+ if (mapped !== undefined) return mapped;
501
+
502
+ // Lenient on a trailing dot ("us." and "us" both read as intent).
503
+ const prefix = env[BEDROCK_INFERENCE_PREFIX_ENV]?.trim().replace(/\.$/, "");
504
+ const derived = `anthropic.${apiModelId}-v1:0`;
505
+ return prefix ? `${prefix}.${derived}` : derived;
506
+ }
507
+
508
+ /**
509
+ * Translate a canonical Anthropic API model id into a Microsoft Foundry
510
+ * deployment name, in two layers (approved design, T05):
511
+ *
512
+ * 1. `STIGMER_FOUNDRY_DEPLOYMENT_MAP` override, consulted first: Foundry
513
+ * routes by DEPLOYMENT NAME, and the portal lets operators name
514
+ * deployments anything ("my-sonnet-deployment"). This is the escape
515
+ * hatch for those custom names.
516
+ * 2. Deterministic rule: strip a trailing `-YYYYMMDD` snapshot date —
517
+ * Foundry's DEFAULT deployment names are the dateless Claude ids
518
+ * (claude-sonnet-4-5-20250929 -> claude-sonnet-4-5; dateless ids pass
519
+ * through unchanged). Verified against Anthropic's published Foundry
520
+ * model table: every native-catalog id maps onto a real default
521
+ * deployment name. Note this is the INVERSE of toVertexModelId, which
522
+ * keeps the date and reseparates it with `@`.
523
+ *
524
+ * Like the other translations, the result is wire detail only: it rides in
525
+ * the request body's `model` field (Foundry keeps it in the body — see
526
+ * foundry-seam.test.ts — unlike Vertex/Bedrock, which move it into the URL
527
+ * path) and must never escape the adapter into usage metrics or pricing,
528
+ * which key on the canonical id (the canonical-id invariant).
529
+ *
530
+ * Throws the catalog message on a malformed map — defense in depth for
531
+ * paths that construct models without the factories; a normally-booted
532
+ * runner already refused to start in `checkFoundryPrerequisites`.
533
+ */
534
+ export function toFoundryDeploymentName(
535
+ apiModelId: string,
536
+ env: NodeJS.ProcessEnv = process.env,
537
+ ): string {
538
+ const parsed = parseFoundryDeploymentMap(env);
539
+ if (!parsed.ok) throw new Error(parsed.message);
540
+ const mapped = parsed.map.get(apiModelId);
541
+ if (mapped !== undefined) return mapped;
542
+
543
+ return apiModelId.replace(TRAILING_SNAPSHOT_DATE, "");
544
+ }
@@ -74,6 +74,21 @@ export function inferProvider(modelName: string): LlmProvider {
74
74
  );
75
75
  }
76
76
 
77
+ /**
78
+ * {@link inferProvider}, returning null instead of throwing on an unknown
79
+ * prefix. For credential pre-checks that must not preempt the construction
80
+ * path: when the provider cannot be determined here, the caller proceeds and
81
+ * lets `buildChatModel` raise inferProvider's precise message inside its own
82
+ * error handling, instead of a guess being made up front.
83
+ */
84
+ export function tryInferProvider(modelName: string): LlmProvider | null {
85
+ try {
86
+ return inferProvider(modelName);
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
77
92
  /**
78
93
  * Strip an explicit "provider:" prefix from the model name, returning
79
94
  * just the model ID portion. If no explicit prefix is present, returns
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Enforcement semantics for McpServerUsage.enabled_tools (issue #350).
3
+ *
4
+ * The proto contract (agent/v1/spec.proto McpServerUsage.enabled_tools,
5
+ * mcpserver/v1/spec.proto McpServerSpec.default_enabled_tools):
6
+ * - A non-empty enabled_tools on the usage is the allow-list for that server.
7
+ * - An empty usage list falls back to the server's default_enabled_tools.
8
+ * - Both empty means NO restriction — every discovered tool is available.
9
+ *
10
+ * Both harnesses import THIS module so they can never drift on these
11
+ * semantics (the mcp-transport-guard precedent for logic shared across the
12
+ * duplicated resolvers — see the header of shared/mcp-resolver.ts):
13
+ * - The deep-agent harness filters the discovered toolset before it reaches
14
+ * the model (shared/mcp-manager.ts connectMcpServers).
15
+ * - The Cursor harness cannot hide tools (the Cursor SDK's McpServerConfig
16
+ * has no allow-list field), so it denies non-enabled calls in the HITL
17
+ * hook instead (execute-cursor/approval-state.ts mcpServerEnabledTools +
18
+ * the "disabled" arm in hook-script.ts). Same guarantee, fail-closed.
19
+ *
20
+ * Names are bare tool names exactly as reported by tools/list — the same
21
+ * identity space as the sub-agent McpAccess filter and the approval-policy
22
+ * maps. An enabled name the server does not expose is warned and dropped
23
+ * (enforce the intersection): the restriction still holds and the run
24
+ * proceeds with the valid subset; apply-time validation against
25
+ * discovered_capabilities is the server-side follow-up that catches typos.
26
+ */
27
+
28
+ /**
29
+ * Compute the effective allow-list for one resolved MCP server.
30
+ *
31
+ * Returns `undefined` when the server is unrestricted (both lists empty) —
32
+ * the absent-field shape ResolvedMcpServer carries so synthesized attachment
33
+ * servers and the discovery path stay unfiltered by construction.
34
+ */
35
+ export function effectiveEnabledTools(
36
+ usageEnabledTools: readonly string[] | undefined,
37
+ defaultEnabledTools: readonly string[] | undefined,
38
+ ): string[] | undefined {
39
+ if (usageEnabledTools && usageEnabledTools.length > 0) {
40
+ return [...usageEnabledTools];
41
+ }
42
+ if (defaultEnabledTools && defaultEnabledTools.length > 0) {
43
+ return [...defaultEnabledTools];
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ /**
49
+ * Filter a server's discovered tools by its effective allow-list.
50
+ *
51
+ * `undefined` enabledTools → unrestricted, tools pass through untouched.
52
+ * Otherwise only tools whose bare name is on the list survive; enabled names
53
+ * the server does not expose are warned and ignored (warn-and-intersect —
54
+ * a stale or mistyped name must narrow the toolset, never widen it or fail
55
+ * the run).
56
+ */
57
+ export function filterToolsByEnabledTools<T extends { name: string }>(
58
+ slug: string,
59
+ tools: readonly T[],
60
+ enabledTools: readonly string[] | undefined,
61
+ ): T[] {
62
+ if (!enabledTools) {
63
+ return [...tools];
64
+ }
65
+
66
+ const allowed = new Set(enabledTools);
67
+ const filtered = tools.filter((tool) => allowed.has(tool.name));
68
+
69
+ const discovered = new Set(tools.map((t) => t.name));
70
+ const unknown = enabledTools.filter((name) => !discovered.has(name));
71
+ if (unknown.length > 0) {
72
+ console.warn(
73
+ `[MCP] Server '${slug}': enabled_tools lists [${unknown.join(", ")}] ` +
74
+ `which the server does not expose — ignoring (the run proceeds with ` +
75
+ `the ${filtered.length} matching tool(s)). Fix the agent's ` +
76
+ `enabled_tools to match the server's discovered tools.`,
77
+ );
78
+ }
79
+
80
+ console.log(
81
+ `[MCP] Server '${slug}': enabled_tools restricts ${tools.length} ` +
82
+ `discovered tool(s) to ${filtered.length}`,
83
+ );
84
+
85
+ return filtered;
86
+ }
87
+
88
+ /**
89
+ * Collect the restricted servers' allow-lists keyed by slug — the shape the
90
+ * Cursor harness writes into the approval state file (mcpServerEnabledTools)
91
+ * for the hook's "disabled" arm. Unrestricted servers are ABSENT (the hook
92
+ * treats an absent slug as unrestricted), so the common no-restriction case
93
+ * stays an empty object.
94
+ */
95
+ export function enabledToolsBySlug(
96
+ servers: readonly { slug: string; enabledTools?: string[] }[],
97
+ ): Record<string, string[]> {
98
+ const bySlug: Record<string, string[]> = {};
99
+ for (const server of servers) {
100
+ if (server.enabledTools) {
101
+ bySlug[server.slug] = [...server.enabledTools];
102
+ }
103
+ }
104
+ return bySlug;
105
+ }