stitchkit 0.93.0 → 0.94.1

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 (1082) hide show
  1. package/CHANGELOG.md +198 -0
  2. package/README.md +5 -2
  3. package/dist/agent-runtime/children-control.d.ts +6 -0
  4. package/dist/agent-runtime/children-control.d.ts.map +1 -0
  5. package/dist/agent-runtime/children-spawn.d.ts +6 -0
  6. package/dist/agent-runtime/children-spawn.d.ts.map +1 -0
  7. package/dist/agent-runtime/children-state.d.ts +46 -0
  8. package/dist/agent-runtime/children-state.d.ts.map +1 -0
  9. package/dist/agent-runtime/children-usage.d.ts +8 -0
  10. package/dist/agent-runtime/children-usage.d.ts.map +1 -0
  11. package/dist/agent-runtime/children.d.ts +11 -14
  12. package/dist/agent-runtime/children.d.ts.map +1 -1
  13. package/dist/agent-runtime/coding-shell-process.d.ts.map +1 -1
  14. package/dist/agent-runtime/coding-tool-contract.d.ts +2 -1
  15. package/dist/agent-runtime/coding-tool-contract.d.ts.map +1 -1
  16. package/dist/agent-runtime/coding-tool-listing.d.ts.map +1 -1
  17. package/dist/agent-runtime/coding-tool-search-patch.d.ts.map +1 -1
  18. package/dist/agent-runtime/contained-darwin.d.ts +38 -0
  19. package/dist/agent-runtime/contained-darwin.d.ts.map +1 -0
  20. package/dist/agent-runtime/contained-files.d.ts +11 -26
  21. package/dist/agent-runtime/contained-files.d.ts.map +1 -1
  22. package/dist/agent-runtime/contained-scan.d.ts +21 -0
  23. package/dist/agent-runtime/contained-scan.d.ts.map +1 -0
  24. package/dist/agent-runtime/contained-write.d.ts +9 -0
  25. package/dist/agent-runtime/contained-write.d.ts.map +1 -0
  26. package/dist/agent-runtime/deferred-tool-types.d.ts +4 -3
  27. package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
  28. package/dist/agent-runtime/events.d.ts +1 -1
  29. package/dist/agent-runtime/events.d.ts.map +1 -1
  30. package/dist/agent-runtime/harness-control.d.ts +0 -1
  31. package/dist/agent-runtime/harness-control.d.ts.map +1 -1
  32. package/dist/agent-runtime/harness.d.ts +0 -5
  33. package/dist/agent-runtime/harness.d.ts.map +1 -1
  34. package/dist/agent-runtime/managed-tools.d.ts +3 -2
  35. package/dist/agent-runtime/managed-tools.d.ts.map +1 -1
  36. package/dist/agent-runtime/observability.d.ts +1 -1
  37. package/dist/agent-runtime/observability.d.ts.map +1 -1
  38. package/dist/agent-runtime/openrouter.d.ts +29 -0
  39. package/dist/agent-runtime/openrouter.d.ts.map +1 -0
  40. package/dist/agent-runtime/projections.d.ts +1 -1
  41. package/dist/agent-runtime/projections.d.ts.map +1 -1
  42. package/dist/agent-runtime/run-acquisition.d.ts +17 -0
  43. package/dist/agent-runtime/run-acquisition.d.ts.map +1 -0
  44. package/dist/agent-runtime/run-execution-state.d.ts +133 -0
  45. package/dist/agent-runtime/run-execution-state.d.ts.map +1 -0
  46. package/dist/agent-runtime/run-execution.d.ts +17 -33
  47. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  48. package/dist/agent-runtime/run-failure.d.ts +18 -0
  49. package/dist/agent-runtime/run-failure.d.ts.map +1 -0
  50. package/dist/agent-runtime/run-model-attempts.d.ts +6 -0
  51. package/dist/agent-runtime/run-model-attempts.d.ts.map +1 -0
  52. package/dist/agent-runtime/run-prompt-history.d.ts +58 -0
  53. package/dist/agent-runtime/run-prompt-history.d.ts.map +1 -0
  54. package/dist/agent-runtime/run-provider-ledger.d.ts +26 -0
  55. package/dist/agent-runtime/run-provider-ledger.d.ts.map +1 -0
  56. package/dist/agent-runtime/run-stream-parts.d.ts +17 -0
  57. package/dist/agent-runtime/run-stream-parts.d.ts.map +1 -0
  58. package/dist/agent-runtime/run-terminal.d.ts +11 -0
  59. package/dist/agent-runtime/run-terminal.d.ts.map +1 -0
  60. package/dist/agent-runtime/run-turn-preparation.d.ts +22 -0
  61. package/dist/agent-runtime/run-turn-preparation.d.ts.map +1 -0
  62. package/dist/agent-runtime/runtime-admission-gate.d.ts +29 -0
  63. package/dist/agent-runtime/runtime-admission-gate.d.ts.map +1 -0
  64. package/dist/agent-runtime/runtime-control.d.ts +9 -0
  65. package/dist/agent-runtime/runtime-control.d.ts.map +1 -0
  66. package/dist/agent-runtime/runtime-recovery.d.ts +10 -0
  67. package/dist/agent-runtime/runtime-recovery.d.ts.map +1 -0
  68. package/dist/agent-runtime/runtime-state.d.ts +36 -0
  69. package/dist/agent-runtime/runtime-state.d.ts.map +1 -0
  70. package/dist/agent-runtime/runtime-submit.d.ts +5 -0
  71. package/dist/agent-runtime/runtime-submit.d.ts.map +1 -0
  72. package/dist/agent-runtime/runtime.d.ts +10 -5
  73. package/dist/agent-runtime/runtime.d.ts.map +1 -1
  74. package/dist/agent-runtime/schedule-records.d.ts +34 -0
  75. package/dist/agent-runtime/schedule-records.d.ts.map +1 -0
  76. package/dist/agent-runtime/schedules.d.ts +34 -0
  77. package/dist/agent-runtime/schedules.d.ts.map +1 -1
  78. package/dist/agent-runtime/sqlite-bun.d.ts +12 -0
  79. package/dist/agent-runtime/sqlite-bun.d.ts.map +1 -0
  80. package/dist/agent-runtime/sqlite-events.d.ts +5 -0
  81. package/dist/agent-runtime/sqlite-events.d.ts.map +1 -0
  82. package/dist/agent-runtime/sqlite-history.d.ts +7 -0
  83. package/dist/agent-runtime/sqlite-history.d.ts.map +1 -0
  84. package/dist/agent-runtime/sqlite-ledger.d.ts +7 -0
  85. package/dist/agent-runtime/sqlite-ledger.d.ts.map +1 -0
  86. package/dist/agent-runtime/sqlite-node.d.ts +12 -0
  87. package/dist/agent-runtime/sqlite-node.d.ts.map +1 -0
  88. package/dist/agent-runtime/sqlite-reads.d.ts +14 -0
  89. package/dist/agent-runtime/sqlite-reads.d.ts.map +1 -0
  90. package/dist/agent-runtime/sqlite-rows.d.ts +178 -0
  91. package/dist/agent-runtime/sqlite-rows.d.ts.map +1 -0
  92. package/dist/agent-runtime/sqlite-schema.d.ts +7 -0
  93. package/dist/agent-runtime/sqlite-schema.d.ts.map +1 -0
  94. package/dist/agent-runtime/sqlite-transactions.d.ts +25 -0
  95. package/dist/agent-runtime/sqlite-transactions.d.ts.map +1 -0
  96. package/dist/agent-runtime/sqlite.d.ts +10 -6
  97. package/dist/agent-runtime/sqlite.d.ts.map +1 -1
  98. package/dist/agent-runtime/store-archive.d.ts +16 -0
  99. package/dist/agent-runtime/store-archive.d.ts.map +1 -0
  100. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +434 -0
  101. package/dist/agent-runtime/store-conformance-lifecycle.d.ts.map +1 -0
  102. package/dist/agent-runtime/store-conformance-ordering.d.ts +18 -0
  103. package/dist/agent-runtime/store-conformance-ordering.d.ts.map +1 -0
  104. package/dist/agent-runtime/store-conformance-support.d.ts +130 -0
  105. package/dist/agent-runtime/store-conformance-support.d.ts.map +1 -0
  106. package/dist/agent-runtime/store-conformance-terminal.d.ts +12 -0
  107. package/dist/agent-runtime/store-conformance-terminal.d.ts.map +1 -0
  108. package/dist/agent-runtime/store-conformance.d.ts +40 -0
  109. package/dist/agent-runtime/store-conformance.d.ts.map +1 -0
  110. package/dist/agent-runtime/store-create.d.ts +11 -0
  111. package/dist/agent-runtime/store-create.d.ts.map +1 -0
  112. package/dist/agent-runtime/store-driver-contract.d.ts +814 -0
  113. package/dist/agent-runtime/store-driver-contract.d.ts.map +1 -0
  114. package/dist/agent-runtime/store-events.d.ts +7 -89
  115. package/dist/agent-runtime/store-events.d.ts.map +1 -1
  116. package/dist/agent-runtime/store-memory.d.ts +4 -0
  117. package/dist/agent-runtime/store-memory.d.ts.map +1 -0
  118. package/dist/agent-runtime/store-mutate.d.ts +13 -0
  119. package/dist/agent-runtime/store-mutate.d.ts.map +1 -0
  120. package/dist/agent-runtime/store-purge.d.ts +1 -1
  121. package/dist/agent-runtime/store-purge.d.ts.map +1 -1
  122. package/dist/agent-runtime/store-reads.d.ts +29 -0
  123. package/dist/agent-runtime/store-reads.d.ts.map +1 -0
  124. package/dist/agent-runtime/store-reduce-history.d.ts +10 -0
  125. package/dist/agent-runtime/store-reduce-history.d.ts.map +1 -0
  126. package/dist/agent-runtime/store-reduce-run.d.ts +14 -0
  127. package/dist/agent-runtime/store-reduce-run.d.ts.map +1 -0
  128. package/dist/agent-runtime/store-reduce-shared.d.ts +76 -0
  129. package/dist/agent-runtime/store-reduce-shared.d.ts.map +1 -0
  130. package/dist/agent-runtime/store-reduce-terminal.d.ts +6 -0
  131. package/dist/agent-runtime/store-reduce-terminal.d.ts.map +1 -0
  132. package/dist/agent-runtime/store-reducer.d.ts +24 -0
  133. package/dist/agent-runtime/store-reducer.d.ts.map +1 -0
  134. package/dist/agent-runtime/store-snapshot.d.ts +19 -0
  135. package/dist/agent-runtime/store-snapshot.d.ts.map +1 -0
  136. package/dist/agent-runtime/store.d.ts +1 -1
  137. package/dist/agent-runtime/store.d.ts.map +1 -1
  138. package/dist/application/admission-rate.d.ts +21 -0
  139. package/dist/application/admission-rate.d.ts.map +1 -0
  140. package/dist/application/admission-run.d.ts +8 -0
  141. package/dist/application/admission-run.d.ts.map +1 -0
  142. package/dist/application/admission.d.ts +1 -1
  143. package/dist/application/admission.d.ts.map +1 -1
  144. package/dist/application/diagnostic-journal-lock.d.ts +9 -34
  145. package/dist/application/diagnostic-journal-lock.d.ts.map +1 -1
  146. package/dist/application/diagnostic-journal-manager.d.ts.map +1 -1
  147. package/dist/application/diagnostic-journal-storage.d.ts.map +1 -1
  148. package/dist/application/events.d.ts +1 -1
  149. package/dist/application/events.d.ts.map +1 -1
  150. package/dist/application/file-state-store.d.ts +23 -0
  151. package/dist/application/file-state-store.d.ts.map +1 -0
  152. package/dist/application/health.d.ts +1 -1
  153. package/dist/application/health.d.ts.map +1 -1
  154. package/dist/application/kernel-admission.d.ts +8 -0
  155. package/dist/application/kernel-admission.d.ts.map +1 -0
  156. package/dist/application/kernel-contract.d.ts +142 -0
  157. package/dist/application/kernel-contract.d.ts.map +1 -0
  158. package/dist/application/kernel-resource-context.d.ts +24 -0
  159. package/dist/application/kernel-resource-context.d.ts.map +1 -0
  160. package/dist/application/kernel-restart.d.ts +5 -0
  161. package/dist/application/kernel-restart.d.ts.map +1 -0
  162. package/dist/application/kernel-rollback.d.ts +4 -0
  163. package/dist/application/kernel-rollback.d.ts.map +1 -0
  164. package/dist/application/kernel-shutdown.d.ts +6 -0
  165. package/dist/application/kernel-shutdown.d.ts.map +1 -0
  166. package/dist/application/kernel-start.d.ts +20 -0
  167. package/dist/application/kernel-start.d.ts.map +1 -0
  168. package/dist/application/kernel-state.d.ts +116 -0
  169. package/dist/application/kernel-state.d.ts.map +1 -0
  170. package/dist/application/kernel.d.ts +9 -140
  171. package/dist/application/kernel.d.ts.map +1 -1
  172. package/dist/application/latest-sink.d.ts +1 -1
  173. package/dist/application/latest-sink.d.ts.map +1 -1
  174. package/dist/application/notification-outbox.d.ts.map +1 -1
  175. package/dist/application/opentelemetry.d.ts +1 -1
  176. package/dist/application/opentelemetry.d.ts.map +1 -1
  177. package/dist/application/schedule.d.ts +0 -1
  178. package/dist/application/schedule.d.ts.map +1 -1
  179. package/dist/application/watch-hub-core.d.ts +122 -0
  180. package/dist/application/watch-hub-core.d.ts.map +1 -0
  181. package/dist/application/watch-hub.d.ts +3 -3
  182. package/dist/application/watch-hub.d.ts.map +1 -1
  183. package/dist/browser/client-executors.d.ts +14 -0
  184. package/dist/browser/client-executors.d.ts.map +1 -0
  185. package/dist/browser/client-multipart.d.ts +1 -1
  186. package/dist/browser/client-multipart.d.ts.map +1 -1
  187. package/dist/browser/client-url.d.ts +1 -1
  188. package/dist/browser/client-url.d.ts.map +1 -1
  189. package/dist/browser/client.d.ts +3 -2
  190. package/dist/browser/client.d.ts.map +1 -1
  191. package/dist/browser/contract-stream.d.ts +1 -1
  192. package/dist/browser/contract-stream.d.ts.map +1 -1
  193. package/dist/browser/http-fetch.d.ts +22 -0
  194. package/dist/browser/http-fetch.d.ts.map +1 -0
  195. package/dist/browser/http.d.ts +2 -4
  196. package/dist/browser/http.d.ts.map +1 -1
  197. package/dist/browser/live-state-core.d.ts +63 -0
  198. package/dist/browser/live-state-core.d.ts.map +1 -0
  199. package/dist/browser/live-state.d.ts.map +1 -1
  200. package/dist/browser/realtime-client.d.ts +26 -0
  201. package/dist/browser/realtime-client.d.ts.map +1 -0
  202. package/dist/browser/resumable.d.ts +1 -28
  203. package/dist/browser/resumable.d.ts.map +1 -1
  204. package/dist/browser/retained.d.ts.map +1 -0
  205. package/dist/browser/socket-io-connection.d.ts +82 -0
  206. package/dist/browser/socket-io-connection.d.ts.map +1 -0
  207. package/dist/browser/socket-io-peer.d.ts +20 -0
  208. package/dist/browser/socket-io-peer.d.ts.map +1 -0
  209. package/dist/browser/socket-io-trace.d.ts +31 -0
  210. package/dist/browser/socket-io-trace.d.ts.map +1 -0
  211. package/dist/browser/socket-io.d.ts +24 -18
  212. package/dist/browser/socket-io.d.ts.map +1 -1
  213. package/dist/browser/stream.d.ts +14 -2
  214. package/dist/browser/stream.d.ts.map +1 -1
  215. package/dist/contract/client-types.d.ts +134 -0
  216. package/dist/contract/client-types.d.ts.map +1 -0
  217. package/dist/contract/define-validation.d.ts +30 -0
  218. package/dist/contract/define-validation.d.ts.map +1 -0
  219. package/dist/contract/define.d.ts +47 -394
  220. package/dist/contract/define.d.ts.map +1 -1
  221. package/dist/contract/normalize.d.ts +56 -0
  222. package/dist/contract/normalize.d.ts.map +1 -0
  223. package/dist/contract/runtime-context.d.ts +131 -0
  224. package/dist/contract/runtime-context.d.ts.map +1 -0
  225. package/dist/contract/tool-options.d.ts +105 -0
  226. package/dist/contract/tool-options.d.ts.map +1 -0
  227. package/dist/contract/tool-view.d.ts +148 -0
  228. package/dist/contract/tool-view.d.ts.map +1 -0
  229. package/dist/declaration/declaration.d.ts.map +1 -0
  230. package/dist/durability/contract.d.ts +259 -0
  231. package/dist/durability/contract.d.ts.map +1 -0
  232. package/dist/durability/effect.d.ts +24 -0
  233. package/dist/durability/effect.d.ts.map +1 -0
  234. package/dist/durability/engine.d.ts +14 -0
  235. package/dist/durability/engine.d.ts.map +1 -0
  236. package/dist/durability/events.d.ts +103 -0
  237. package/dist/durability/events.d.ts.map +1 -0
  238. package/dist/durability/json.d.ts +3 -0
  239. package/dist/durability/json.d.ts.map +1 -0
  240. package/dist/durability/ledger.d.ts +27 -0
  241. package/dist/durability/ledger.d.ts.map +1 -0
  242. package/dist/durability/parks.d.ts +22 -0
  243. package/dist/durability/parks.d.ts.map +1 -0
  244. package/dist/durability/scheduler.d.ts +30 -0
  245. package/dist/durability/scheduler.d.ts.map +1 -0
  246. package/dist/entrypoints/agent-runtime/browser.d.ts +5 -0
  247. package/dist/entrypoints/agent-runtime/browser.d.ts.map +1 -0
  248. package/dist/entrypoints/agent-runtime/browser.js +124 -0
  249. package/dist/entrypoints/agent-runtime/coding-tools.d.ts +2 -0
  250. package/dist/entrypoints/agent-runtime/coding-tools.d.ts.map +1 -0
  251. package/dist/entrypoints/agent-runtime/coding-tools.js +22 -0
  252. package/dist/entrypoints/agent-runtime/harness.d.ts +2 -0
  253. package/dist/entrypoints/agent-runtime/harness.d.ts.map +1 -0
  254. package/dist/entrypoints/agent-runtime/harness.js +739 -0
  255. package/dist/entrypoints/agent-runtime/openrouter.d.ts +2 -0
  256. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -0
  257. package/dist/entrypoints/agent-runtime/openrouter.js +270 -0
  258. package/dist/entrypoints/agent-runtime/sandbox.d.ts +5 -0
  259. package/dist/entrypoints/agent-runtime/sandbox.d.ts.map +1 -0
  260. package/dist/entrypoints/agent-runtime/sandbox.js +797 -0
  261. package/dist/entrypoints/agent-runtime/sqlite/bun.d.ts +2 -0
  262. package/dist/entrypoints/agent-runtime/sqlite/bun.d.ts.map +1 -0
  263. package/dist/entrypoints/agent-runtime/sqlite/bun.js +44 -0
  264. package/dist/entrypoints/agent-runtime/sqlite/node.d.ts +2 -0
  265. package/dist/entrypoints/agent-runtime/sqlite/node.d.ts.map +1 -0
  266. package/dist/entrypoints/agent-runtime/sqlite/node.js +46 -0
  267. package/dist/entrypoints/agent-runtime/testing.d.ts +4 -0
  268. package/dist/entrypoints/agent-runtime/testing.d.ts.map +1 -0
  269. package/dist/entrypoints/agent-runtime/testing.js +1116 -0
  270. package/dist/entrypoints/agent-runtime.d.ts +42 -0
  271. package/dist/entrypoints/agent-runtime.d.ts.map +1 -0
  272. package/dist/entrypoints/agent-runtime.js +2670 -0
  273. package/dist/entrypoints/application/diagnostic-journal.d.ts +21 -0
  274. package/dist/entrypoints/application/diagnostic-journal.d.ts.map +1 -0
  275. package/dist/entrypoints/application/diagnostic-journal.js +492 -0
  276. package/dist/entrypoints/application/grammy.d.ts +2 -0
  277. package/dist/entrypoints/application/grammy.d.ts.map +1 -0
  278. package/dist/entrypoints/application/grammy.js +169 -0
  279. package/dist/entrypoints/application/opentelemetry.d.ts +2 -0
  280. package/dist/entrypoints/application/opentelemetry.d.ts.map +1 -0
  281. package/dist/entrypoints/application/opentelemetry.js +250 -0
  282. package/dist/entrypoints/application/schemas.d.ts +15 -0
  283. package/dist/entrypoints/application/schemas.d.ts.map +1 -0
  284. package/dist/entrypoints/application/schemas.js +27 -0
  285. package/dist/entrypoints/application.d.ts +23 -0
  286. package/dist/entrypoints/application.d.ts.map +1 -0
  287. package/dist/entrypoints/application.js +2016 -0
  288. package/dist/entrypoints/bin/upgrade-cli.d.ts.map +1 -0
  289. package/dist/entrypoints/bin/upgrade-cli.js +177 -0
  290. package/dist/entrypoints/cli.d.ts +44 -0
  291. package/dist/entrypoints/cli.d.ts.map +1 -0
  292. package/dist/entrypoints/cli.js +773 -0
  293. package/dist/entrypoints/contract.d.ts +12 -0
  294. package/dist/entrypoints/contract.d.ts.map +1 -0
  295. package/dist/entrypoints/contract.js +64 -0
  296. package/dist/entrypoints/declaration.d.ts +2 -0
  297. package/dist/entrypoints/declaration.d.ts.map +1 -0
  298. package/dist/entrypoints/declaration.js +183 -0
  299. package/dist/entrypoints/files.d.ts +5 -0
  300. package/dist/entrypoints/files.d.ts.map +1 -0
  301. package/dist/entrypoints/files.js +111 -0
  302. package/dist/entrypoints/geo.d.ts +3 -0
  303. package/dist/entrypoints/geo.d.ts.map +1 -0
  304. package/dist/entrypoints/geo.js +245 -0
  305. package/dist/entrypoints/google.d.ts +2 -0
  306. package/dist/entrypoints/google.d.ts.map +1 -0
  307. package/dist/entrypoints/google.js +175 -0
  308. package/dist/entrypoints/index.d.ts +17 -0
  309. package/dist/entrypoints/index.d.ts.map +1 -0
  310. package/dist/entrypoints/index.js +764 -0
  311. package/dist/entrypoints/live.d.ts +19 -0
  312. package/dist/entrypoints/live.d.ts.map +1 -0
  313. package/dist/entrypoints/live.js +302 -0
  314. package/dist/entrypoints/node.d.ts +19 -0
  315. package/dist/entrypoints/node.d.ts.map +1 -0
  316. package/dist/entrypoints/node.js +308 -0
  317. package/dist/entrypoints/oauth.d.ts +2 -0
  318. package/dist/entrypoints/oauth.d.ts.map +1 -0
  319. package/dist/entrypoints/oauth.js +170 -0
  320. package/dist/entrypoints/observability.d.ts +19 -0
  321. package/dist/entrypoints/observability.d.ts.map +1 -0
  322. package/dist/entrypoints/observability.js +567 -0
  323. package/dist/entrypoints/primitives.d.ts +3 -0
  324. package/dist/entrypoints/primitives.d.ts.map +1 -0
  325. package/dist/entrypoints/primitives.js +749 -0
  326. package/dist/entrypoints/react.d.ts +5 -0
  327. package/dist/entrypoints/react.d.ts.map +1 -0
  328. package/dist/entrypoints/react.js +403 -0
  329. package/dist/entrypoints/release.d.ts +15 -0
  330. package/dist/entrypoints/release.d.ts.map +1 -0
  331. package/dist/entrypoints/release.js +196 -0
  332. package/dist/entrypoints/remote.d.ts +9 -0
  333. package/dist/entrypoints/remote.d.ts.map +1 -0
  334. package/dist/entrypoints/remote.js +66 -0
  335. package/dist/entrypoints/server.d.ts +39 -0
  336. package/dist/entrypoints/server.d.ts.map +1 -0
  337. package/dist/entrypoints/server.js +2009 -0
  338. package/dist/entrypoints/telegram.d.ts +3 -0
  339. package/dist/entrypoints/telegram.d.ts.map +1 -0
  340. package/dist/entrypoints/telegram.js +224 -0
  341. package/dist/entrypoints/testing.d.ts +10 -0
  342. package/dist/entrypoints/testing.d.ts.map +1 -0
  343. package/dist/entrypoints/testing.js +1377 -0
  344. package/dist/entrypoints/tools/connections.d.ts +19 -0
  345. package/dist/entrypoints/tools/connections.d.ts.map +1 -0
  346. package/dist/entrypoints/tools/connections.js +1110 -0
  347. package/dist/entrypoints/tools/contract.d.ts +29 -0
  348. package/dist/entrypoints/tools/contract.d.ts.map +1 -0
  349. package/dist/entrypoints/tools/contract.js +24 -0
  350. package/dist/entrypoints/tools/invoker.d.ts +9 -0
  351. package/dist/entrypoints/tools/invoker.d.ts.map +1 -0
  352. package/dist/entrypoints/tools/invoker.js +20 -0
  353. package/dist/entrypoints/tools.d.ts +54 -0
  354. package/dist/entrypoints/tools.d.ts.map +1 -0
  355. package/dist/entrypoints/tools.js +3009 -0
  356. package/dist/entrypoints/tracking/server.d.ts +15 -0
  357. package/dist/entrypoints/tracking/server.d.ts.map +1 -0
  358. package/dist/entrypoints/tracking.d.ts +24 -0
  359. package/dist/entrypoints/tracking.d.ts.map +1 -0
  360. package/dist/entrypoints/tracking.js +1140 -0
  361. package/dist/files/boundary.d.ts.map +1 -1
  362. package/dist/files/file-io.d.ts +14 -0
  363. package/dist/files/file-io.d.ts.map +1 -0
  364. package/dist/google/google.d.ts.map +1 -0
  365. package/dist/index-0b1ess5e.js +38 -0
  366. package/dist/index-1j8pm5t0.js +412 -0
  367. package/dist/index-1zbbzgfh.js +89 -0
  368. package/dist/index-2bxbyab0.js +47 -0
  369. package/dist/index-2gxzjvyr.js +266 -0
  370. package/dist/index-35mh5bhj.js +177 -0
  371. package/dist/index-48ffdxgk.js +6 -0
  372. package/dist/index-4gcnakhx.js +82 -0
  373. package/dist/index-55hkhm67.js +343 -0
  374. package/dist/index-79z7m7dt.js +675 -0
  375. package/dist/index-7f68ghdn.js +3618 -0
  376. package/dist/index-7p1f0vp2.js +154 -0
  377. package/dist/index-83bdg97s.js +16 -0
  378. package/dist/index-863ea9jb.js +154 -0
  379. package/dist/index-8p52kd5p.js +242 -0
  380. package/dist/index-d9pk3td4.js +326 -0
  381. package/dist/index-dce5wxcq.js +63 -0
  382. package/dist/index-e01r054k.js +105 -0
  383. package/dist/index-ensd0r74.js +595 -0
  384. package/dist/index-eqqvgdb3.js +46 -0
  385. package/dist/index-gxrt5h6v.js +341 -0
  386. package/dist/index-h6eeys1v.js +211 -0
  387. package/dist/index-ham5sz8m.js +734 -0
  388. package/dist/index-het2he5g.js +1387 -0
  389. package/dist/index-hffjpmq9.js +30 -0
  390. package/dist/index-hmp4800j.js +51 -0
  391. package/dist/index-k30h66yd.js +317 -0
  392. package/dist/index-k5hsfc3j.js +31 -0
  393. package/dist/index-khtgb21r.js +92 -0
  394. package/dist/index-m9zn6cpq.js +51 -0
  395. package/dist/index-ndddxtyx.js +324 -0
  396. package/dist/index-ngfhvfpd.js +30 -0
  397. package/dist/index-np4m8hd3.js +1205 -0
  398. package/dist/index-p3vsv1fb.js +3493 -0
  399. package/dist/index-p5r7qpdd.js +85 -0
  400. package/dist/index-p9e0w8hs.js +1084 -0
  401. package/dist/index-p9sh0xx4.js +64 -0
  402. package/dist/index-paz6sgdp.js +371 -0
  403. package/dist/index-px2gm2jp.js +448 -0
  404. package/dist/index-qwhynv6x.js +103 -0
  405. package/dist/index-s812ycat.js +65 -0
  406. package/dist/index-sp1tzwnb.js +281 -0
  407. package/dist/index-t9rhjr9f.js +2306 -0
  408. package/dist/index-v260df89.js +342 -0
  409. package/dist/index-w906953s.js +946 -0
  410. package/dist/index-wdkt63w3.js +214 -0
  411. package/dist/index-wqgjfstn.js +18 -0
  412. package/dist/index-wsm5w4ee.js +1023 -0
  413. package/dist/index-xw3s75nj.js +100 -0
  414. package/dist/index-yw4fzmdz.js +268 -0
  415. package/dist/index-zfrhfn82.js +85 -0
  416. package/dist/index-znfs20ss.js +98 -0
  417. package/dist/internal/atomic-file.d.ts +23 -2
  418. package/dist/internal/atomic-file.d.ts.map +1 -1
  419. package/dist/internal/backoff.d.ts +29 -0
  420. package/dist/internal/backoff.d.ts.map +1 -0
  421. package/dist/internal/canonical-json.d.ts +21 -11
  422. package/dist/internal/canonical-json.d.ts.map +1 -1
  423. package/dist/internal/channel.d.ts.map +1 -0
  424. package/dist/internal/exclusive-lock.d.ts +51 -0
  425. package/dist/internal/exclusive-lock.d.ts.map +1 -0
  426. package/dist/internal/logger.d.ts.map +1 -0
  427. package/dist/internal/process-identity.d.ts +47 -0
  428. package/dist/internal/process-identity.d.ts.map +1 -0
  429. package/dist/internal/request.d.ts.map +1 -0
  430. package/dist/internal/stable-digest.d.ts +0 -43
  431. package/dist/internal/stable-digest.d.ts.map +1 -1
  432. package/dist/internal/typed.d.ts +0 -8
  433. package/dist/internal/typed.d.ts.map +1 -1
  434. package/dist/internal/with-exclusive-lock.d.ts +67 -0
  435. package/dist/internal/with-exclusive-lock.d.ts.map +1 -0
  436. package/dist/internal/zod-issues.d.ts +38 -0
  437. package/dist/internal/zod-issues.d.ts.map +1 -0
  438. package/dist/json-schema/dialect.d.ts +17 -0
  439. package/dist/json-schema/dialect.d.ts.map +1 -0
  440. package/dist/json-schema/json-schema.d.ts.map +1 -0
  441. package/dist/live/watch-client.d.ts.map +1 -1
  442. package/dist/live/watch-delta.d.ts.map +1 -1
  443. package/dist/oauth/authorization-code.d.ts +57 -0
  444. package/dist/oauth/authorization-code.d.ts.map +1 -0
  445. package/dist/observability/audit.d.ts +3 -3
  446. package/dist/observability/audit.d.ts.map +1 -1
  447. package/dist/observability/bounded-logger.d.ts +1 -1
  448. package/dist/observability/bounded-logger.d.ts.map +1 -1
  449. package/dist/observability/bounded-sink.d.ts +81 -0
  450. package/dist/observability/bounded-sink.d.ts.map +1 -0
  451. package/dist/observability/context.d.ts +1 -1
  452. package/dist/observability/context.d.ts.map +1 -1
  453. package/dist/observability/event.d.ts +2 -1
  454. package/dist/observability/event.d.ts.map +1 -1
  455. package/dist/observability/work.d.ts +1 -1
  456. package/dist/observability/work.d.ts.map +1 -1
  457. package/dist/primitives/audit.d.ts +1 -1
  458. package/dist/primitives/audit.d.ts.map +1 -1
  459. package/dist/primitives/export-operation.d.ts +4 -2
  460. package/dist/primitives/export-operation.d.ts.map +1 -1
  461. package/dist/realtime/registry.d.ts +0 -5
  462. package/dist/realtime/registry.d.ts.map +1 -1
  463. package/dist/realtime/socket.d.ts +1 -1
  464. package/dist/realtime/socket.d.ts.map +1 -1
  465. package/dist/server/bun.d.ts +0 -1
  466. package/dist/server/bun.d.ts.map +1 -1
  467. package/dist/server/context-contribution.d.ts +1 -1
  468. package/dist/server/context-contribution.d.ts.map +1 -1
  469. package/dist/server/context.d.ts +2 -2
  470. package/dist/server/context.d.ts.map +1 -1
  471. package/dist/server/contract-method.d.ts +15 -0
  472. package/dist/server/contract-method.d.ts.map +1 -0
  473. package/dist/server/contract-stream.d.ts +1 -1
  474. package/dist/server/contract-stream.d.ts.map +1 -1
  475. package/dist/server/create.d.ts +8 -0
  476. package/dist/server/create.d.ts.map +1 -1
  477. package/dist/server/endpoint-dispatch.d.ts +10 -0
  478. package/dist/server/endpoint-dispatch.d.ts.map +1 -0
  479. package/dist/server/endpoint-response.d.ts +19 -0
  480. package/dist/server/endpoint-response.d.ts.map +1 -0
  481. package/dist/server/error-dispatch.d.ts +17 -1
  482. package/dist/server/error-dispatch.d.ts.map +1 -1
  483. package/dist/server/error-hook.d.ts +2 -2
  484. package/dist/server/error-hook.d.ts.map +1 -1
  485. package/dist/server/handler-state.d.ts +44 -0
  486. package/dist/server/handler-state.d.ts.map +1 -0
  487. package/dist/server/implement-registry.d.ts +54 -0
  488. package/dist/server/implement-registry.d.ts.map +1 -0
  489. package/dist/server/implement.d.ts +9 -55
  490. package/dist/server/implement.d.ts.map +1 -1
  491. package/dist/server/middleware/auth.d.ts +1 -31
  492. package/dist/server/middleware/auth.d.ts.map +1 -1
  493. package/dist/server/middleware/cors.d.ts +17 -0
  494. package/dist/server/middleware/cors.d.ts.map +1 -1
  495. package/dist/server/middleware/jwt.d.ts +31 -0
  496. package/dist/server/middleware/jwt.d.ts.map +1 -0
  497. package/dist/server/middleware/trust-fence.d.ts +1 -1
  498. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  499. package/dist/server/multipart-reader.d.ts +22 -0
  500. package/dist/server/multipart-reader.d.ts.map +1 -0
  501. package/dist/server/multipart.d.ts +1 -1
  502. package/dist/server/multipart.d.ts.map +1 -1
  503. package/dist/server/oauth/cimd.d.ts +88 -0
  504. package/dist/server/oauth/cimd.d.ts.map +1 -0
  505. package/dist/server/oauth/endpoints.d.ts +39 -0
  506. package/dist/server/oauth/endpoints.d.ts.map +1 -0
  507. package/dist/server/oauth/metadata.d.ts +28 -0
  508. package/dist/server/oauth/metadata.d.ts.map +1 -0
  509. package/dist/server/oauth/provider.d.ts +117 -0
  510. package/dist/server/oauth/provider.d.ts.map +1 -0
  511. package/dist/server/realtime.d.ts +1 -1
  512. package/dist/server/realtime.d.ts.map +1 -1
  513. package/dist/server/request-completion.d.ts +16 -0
  514. package/dist/server/request-completion.d.ts.map +1 -0
  515. package/dist/server/response-metadata.d.ts +1 -1
  516. package/dist/server/response-metadata.d.ts.map +1 -1
  517. package/dist/server/route-table.d.ts +9 -0
  518. package/dist/server/route-table.d.ts.map +1 -0
  519. package/dist/server/stream.d.ts +0 -13
  520. package/dist/server/stream.d.ts.map +1 -1
  521. package/dist/server/streaming-pump.d.ts +66 -0
  522. package/dist/server/streaming-pump.d.ts.map +1 -0
  523. package/dist/server/streaming-route.d.ts +12 -5
  524. package/dist/server/streaming-route.d.ts.map +1 -1
  525. package/dist/server/types.d.ts +10 -4
  526. package/dist/server/types.d.ts.map +1 -1
  527. package/dist/server/unix-client-bun.d.ts.map +1 -1
  528. package/dist/server/unix-client-http1.d.ts +76 -0
  529. package/dist/server/unix-client-http1.d.ts.map +1 -0
  530. package/dist/server/unix-client.d.ts.map +1 -1
  531. package/dist/testing/handler-clients.d.ts +32 -0
  532. package/dist/testing/handler-clients.d.ts.map +1 -0
  533. package/dist/testing/managed-resource-conformance-scenarios.d.ts.map +1 -1
  534. package/dist/testing/realtime-probe.d.ts +33 -0
  535. package/dist/testing/realtime-probe.d.ts.map +1 -0
  536. package/dist/testing/surface-conformance.d.ts +2 -32
  537. package/dist/testing/surface-conformance.d.ts.map +1 -1
  538. package/dist/testing/surface-manifest-digest.d.ts +44 -0
  539. package/dist/testing/surface-manifest-digest.d.ts.map +1 -0
  540. package/dist/testing/surface-manifest.d.ts +30 -4
  541. package/dist/testing/surface-manifest.d.ts.map +1 -1
  542. package/dist/tools/agent.d.ts +1 -1
  543. package/dist/tools/agent.d.ts.map +1 -1
  544. package/dist/tools/cli/args-fields.d.ts +31 -0
  545. package/dist/tools/cli/args-fields.d.ts.map +1 -0
  546. package/dist/tools/cli/args-route.d.ts +42 -0
  547. package/dist/tools/cli/args-route.d.ts.map +1 -0
  548. package/dist/tools/cli/args-view.d.ts +32 -0
  549. package/dist/tools/cli/args-view.d.ts.map +1 -0
  550. package/dist/tools/cli/args.d.ts +80 -0
  551. package/dist/tools/cli/args.d.ts.map +1 -0
  552. package/dist/tools/cli/argument-error.d.ts +5 -0
  553. package/dist/tools/cli/argument-error.d.ts.map +1 -0
  554. package/dist/tools/cli/checkpoint.d.ts +24 -0
  555. package/dist/tools/cli/checkpoint.d.ts.map +1 -0
  556. package/dist/tools/cli/command.d.ts +70 -0
  557. package/dist/tools/cli/command.d.ts.map +1 -0
  558. package/dist/tools/cli/config.d.ts +90 -0
  559. package/dist/tools/cli/config.d.ts.map +1 -0
  560. package/dist/tools/cli/create-cli.d.ts +36 -0
  561. package/dist/tools/cli/create-cli.d.ts.map +1 -0
  562. package/dist/tools/cli/download.d.ts +8 -0
  563. package/dist/tools/cli/download.d.ts.map +1 -0
  564. package/dist/tools/cli/format.d.ts +50 -0
  565. package/dist/tools/cli/format.d.ts.map +1 -0
  566. package/dist/tools/cli/help.d.ts +24 -0
  567. package/dist/tools/cli/help.d.ts.map +1 -0
  568. package/dist/tools/cli/installer.d.ts +34 -0
  569. package/dist/tools/cli/installer.d.ts.map +1 -0
  570. package/dist/tools/cli/invoke.d.ts +144 -0
  571. package/dist/tools/cli/invoke.d.ts.map +1 -0
  572. package/dist/tools/cli/io.d.ts +10 -0
  573. package/dist/tools/cli/io.d.ts.map +1 -0
  574. package/dist/tools/cli/managed-surface.d.ts +30 -0
  575. package/dist/tools/cli/managed-surface.d.ts.map +1 -0
  576. package/dist/tools/cli/manifest.d.ts +80 -0
  577. package/dist/tools/cli/manifest.d.ts.map +1 -0
  578. package/dist/tools/cli/policy.d.ts +27 -0
  579. package/dist/tools/cli/policy.d.ts.map +1 -0
  580. package/dist/tools/cli/prepare.d.ts +14 -0
  581. package/dist/tools/cli/prepare.d.ts.map +1 -0
  582. package/dist/tools/cli/profile.d.ts +40 -0
  583. package/dist/tools/cli/profile.d.ts.map +1 -0
  584. package/dist/tools/cli/run-managed.d.ts +5 -0
  585. package/dist/tools/cli/run-managed.d.ts.map +1 -0
  586. package/dist/tools/cli/run-native.d.ts +9 -0
  587. package/dist/tools/cli/run-native.d.ts.map +1 -0
  588. package/dist/tools/cli/session.d.ts +40 -0
  589. package/dist/tools/cli/session.d.ts.map +1 -0
  590. package/dist/tools/cli/signature.d.ts +81 -0
  591. package/dist/tools/cli/signature.d.ts.map +1 -0
  592. package/dist/tools/cli/stream.d.ts +93 -0
  593. package/dist/tools/cli/stream.d.ts.map +1 -0
  594. package/dist/tools/cli/update.d.ts +145 -0
  595. package/dist/tools/cli/update.d.ts.map +1 -0
  596. package/dist/tools/cli/view.d.ts +12 -0
  597. package/dist/tools/cli/view.d.ts.map +1 -0
  598. package/dist/tools/cli/wait.d.ts +54 -0
  599. package/dist/tools/cli/wait.d.ts.map +1 -0
  600. package/dist/tools/connections/runtime.d.ts +1 -1
  601. package/dist/tools/connections/runtime.d.ts.map +1 -1
  602. package/dist/tools/connections/types.d.ts +3 -3
  603. package/dist/tools/connections/types.d.ts.map +1 -1
  604. package/dist/tools/durability-context.d.ts +1 -1
  605. package/dist/tools/durability-context.d.ts.map +1 -1
  606. package/dist/tools/execute-args.d.ts +23 -0
  607. package/dist/tools/execute-args.d.ts.map +1 -0
  608. package/dist/tools/execute-hooks.d.ts +146 -0
  609. package/dist/tools/execute-hooks.d.ts.map +1 -0
  610. package/dist/tools/execute-result.d.ts +40 -0
  611. package/dist/tools/execute-result.d.ts.map +1 -0
  612. package/dist/tools/execute.d.ts +31 -193
  613. package/dist/tools/execute.d.ts.map +1 -1
  614. package/dist/tools/internal/surface-projector.d.ts +9 -6
  615. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  616. package/dist/tools/internal/tool-view.d.ts +41 -0
  617. package/dist/tools/internal/tool-view.d.ts.map +1 -0
  618. package/dist/tools/invoker.d.ts +13 -4
  619. package/dist/tools/invoker.d.ts.map +1 -1
  620. package/dist/tools/lifecycle.d.ts +1 -1
  621. package/dist/tools/lifecycle.d.ts.map +1 -1
  622. package/dist/tools/list-names.d.ts +3 -3
  623. package/dist/tools/list-names.d.ts.map +1 -1
  624. package/dist/tools/manifest.d.ts +2 -2
  625. package/dist/tools/manifest.d.ts.map +1 -1
  626. package/dist/tools/mcp/app.d.ts +62 -0
  627. package/dist/tools/mcp/app.d.ts.map +1 -0
  628. package/dist/tools/mcp/catalog.d.ts +68 -0
  629. package/dist/tools/mcp/catalog.d.ts.map +1 -0
  630. package/dist/tools/mcp/handler.d.ts +46 -0
  631. package/dist/tools/mcp/handler.d.ts.map +1 -0
  632. package/dist/tools/mcp/mount.d.ts +152 -0
  633. package/dist/tools/mcp/mount.d.ts.map +1 -0
  634. package/dist/tools/mcp/prepare.d.ts +76 -0
  635. package/dist/tools/mcp/prepare.d.ts.map +1 -0
  636. package/dist/tools/mcp/progress.d.ts +46 -0
  637. package/dist/tools/mcp/progress.d.ts.map +1 -0
  638. package/dist/tools/mcp/register.d.ts +36 -0
  639. package/dist/tools/mcp/register.d.ts.map +1 -0
  640. package/dist/tools/mcp/round-context.d.ts +38 -0
  641. package/dist/tools/mcp/round-context.d.ts.map +1 -0
  642. package/dist/tools/mcp/round-policy.d.ts +33 -0
  643. package/dist/tools/mcp/round-policy.d.ts.map +1 -0
  644. package/dist/tools/mcp/round.d.ts +53 -0
  645. package/dist/tools/mcp/round.d.ts.map +1 -0
  646. package/dist/tools/mcp/runtime-tools.d.ts +25 -0
  647. package/dist/tools/mcp/runtime-tools.d.ts.map +1 -0
  648. package/dist/tools/mcp/stdio-signals.d.ts +33 -0
  649. package/dist/tools/mcp/stdio-signals.d.ts.map +1 -0
  650. package/dist/tools/mcp/stdio.d.ts +20 -0
  651. package/dist/tools/mcp/stdio.d.ts.map +1 -0
  652. package/dist/tools/mcp/trace.d.ts +12 -0
  653. package/dist/tools/mcp/trace.d.ts.map +1 -0
  654. package/dist/tools/mount.d.ts +14 -7
  655. package/dist/tools/mount.d.ts.map +1 -1
  656. package/dist/tools/native-definition.d.ts +4 -3
  657. package/dist/tools/native-definition.d.ts.map +1 -1
  658. package/dist/tools/operations/async-operation-binding-types.d.ts +127 -0
  659. package/dist/tools/operations/async-operation-binding-types.d.ts.map +1 -0
  660. package/dist/tools/operations/async-operation-binding.d.ts +28 -0
  661. package/dist/tools/operations/async-operation-binding.d.ts.map +1 -0
  662. package/dist/tools/operations/async-operation-canonical-types.d.ts +110 -0
  663. package/dist/tools/operations/async-operation-canonical-types.d.ts.map +1 -0
  664. package/dist/tools/operations/async-operation-canonical.d.ts +7 -0
  665. package/dist/tools/operations/async-operation-canonical.d.ts.map +1 -0
  666. package/dist/tools/operations/async-operation-contract.d.ts.map +1 -0
  667. package/dist/tools/operations/async-operation-id.d.ts +23 -0
  668. package/dist/tools/operations/async-operation-id.d.ts.map +1 -0
  669. package/dist/tools/operations/async-operation-runtime-tools.d.ts +41 -0
  670. package/dist/tools/operations/async-operation-runtime-tools.d.ts.map +1 -0
  671. package/dist/tools/operations/async-operation-runtime-types.d.ts +69 -0
  672. package/dist/tools/operations/async-operation-runtime-types.d.ts.map +1 -0
  673. package/dist/tools/operations/async-operation-runtime.d.ts +5 -0
  674. package/dist/tools/operations/async-operation-runtime.d.ts.map +1 -0
  675. package/dist/tools/operations/define-wait-tool.d.ts +22 -0
  676. package/dist/tools/operations/define-wait-tool.d.ts.map +1 -0
  677. package/dist/tools/operations/mount-wait.d.ts.map +1 -0
  678. package/dist/tools/operations/wait-core.d.ts.map +1 -0
  679. package/dist/tools/remote.d.ts +1 -1
  680. package/dist/tools/remote.d.ts.map +1 -1
  681. package/dist/tools/runtime-tool.d.ts +13 -4
  682. package/dist/tools/runtime-tool.d.ts.map +1 -1
  683. package/dist/tools/schema/coerce.d.ts.map +1 -0
  684. package/dist/tools/schema/flatten-join.d.ts.map +1 -0
  685. package/dist/tools/schema/flatten.d.ts.map +1 -0
  686. package/dist/tools/schema/portable-formats.d.ts.map +1 -0
  687. package/dist/tools/schema/presentation.d.ts +24 -0
  688. package/dist/tools/schema/presentation.d.ts.map +1 -0
  689. package/dist/tools/schema/schema.d.ts.map +1 -0
  690. package/dist/tools/schema/untyped-properties.d.ts.map +1 -0
  691. package/dist/tools/surface.d.ts +2 -3
  692. package/dist/tools/surface.d.ts.map +1 -1
  693. package/dist/tools/tool-logger.d.ts +1 -1
  694. package/dist/tools/tool-logger.d.ts.map +1 -1
  695. package/dist/tools/toolkit.d.ts +4 -4
  696. package/dist/tools/toolkit.d.ts.map +1 -1
  697. package/dist/tools/transfer/define-download-tool.d.ts +18 -0
  698. package/dist/tools/transfer/define-download-tool.d.ts.map +1 -0
  699. package/dist/tools/transfer/define-upload-tool.d.ts +16 -0
  700. package/dist/tools/transfer/define-upload-tool.d.ts.map +1 -0
  701. package/dist/tools/transfer/define-view-file-tool.d.ts +10 -0
  702. package/dist/tools/transfer/define-view-file-tool.d.ts.map +1 -0
  703. package/dist/tools/transfer/download-core.d.ts +20 -0
  704. package/dist/tools/transfer/download-core.d.ts.map +1 -0
  705. package/dist/tools/transfer/managed-file-error.d.ts +6 -0
  706. package/dist/tools/transfer/managed-file-error.d.ts.map +1 -0
  707. package/dist/tools/transfer/mount-download.d.ts +41 -0
  708. package/dist/tools/transfer/mount-download.d.ts.map +1 -0
  709. package/dist/tools/transfer/mount-upload.d.ts +21 -0
  710. package/dist/tools/transfer/mount-upload.d.ts.map +1 -0
  711. package/dist/tools/transfer/native-result.d.ts.map +1 -0
  712. package/dist/tools/transfer/upload-core.d.ts +4 -0
  713. package/dist/tools/transfer/upload-core.d.ts.map +1 -0
  714. package/dist/tools/transfer/view-file-contract.d.ts.map +1 -0
  715. package/dist/tools/transfer/view-file.d.ts +62 -0
  716. package/dist/tools/transfer/view-file.d.ts.map +1 -0
  717. package/dist/tools/transports.d.ts +1 -1
  718. package/dist/tools/transports.d.ts.map +1 -1
  719. package/dist/tracking/client-listeners.d.ts +30 -0
  720. package/dist/tracking/client-listeners.d.ts.map +1 -0
  721. package/dist/tracking/client-visit.d.ts +61 -0
  722. package/dist/tracking/client-visit.d.ts.map +1 -0
  723. package/dist/tracking/client.d.ts +3 -2
  724. package/dist/tracking/client.d.ts.map +1 -1
  725. package/dist/tracking/contract.d.ts +1 -1
  726. package/dist/tracking/contract.d.ts.map +1 -1
  727. package/llms/agent-runtime-browser.txt +33 -0
  728. package/llms/agent-runtime-coding-tools.txt +58 -0
  729. package/llms/agent-runtime-harness.txt +45 -0
  730. package/llms/agent-runtime-openrouter.txt +22 -0
  731. package/llms/agent-runtime-sandbox.txt +159 -0
  732. package/llms/agent-runtime-sqlite-bun.txt +29 -0
  733. package/llms/agent-runtime-sqlite-node.txt +26 -0
  734. package/llms/agent-runtime-testing.txt +30 -0
  735. package/llms/agent-runtime.2.txt +550 -0
  736. package/llms/agent-runtime.3.txt +311 -0
  737. package/llms/agent-runtime.txt +893 -0
  738. package/llms/application-diagnostic-journal.txt +30 -0
  739. package/llms/application-grammy.txt +27 -0
  740. package/llms/application-opentelemetry.txt +27 -0
  741. package/llms/application-schemas.txt +42 -0
  742. package/llms/application.2.txt +487 -0
  743. package/llms/application.txt +886 -0
  744. package/llms/cli.2.txt +80 -0
  745. package/llms/cli.txt +948 -0
  746. package/llms/contract.txt +606 -0
  747. package/llms/declaration.txt +286 -0
  748. package/llms/files.txt +33 -0
  749. package/llms/geo.txt +114 -0
  750. package/llms/google.txt +27 -0
  751. package/llms/live.txt +471 -0
  752. package/llms/node.txt +43 -0
  753. package/llms/oauth.txt +136 -0
  754. package/llms/observability.txt +893 -0
  755. package/llms/primitives.txt +158 -0
  756. package/llms/react.txt +184 -0
  757. package/llms/release.txt +176 -0
  758. package/llms/remote.txt +25 -0
  759. package/llms/server.2.txt +361 -0
  760. package/llms/server.3.txt +1031 -0
  761. package/llms/server.4.txt +905 -0
  762. package/llms/server.5.txt +250 -0
  763. package/llms/server.txt +996 -0
  764. package/llms/stitchkit.2.txt +836 -0
  765. package/llms/stitchkit.3.txt +147 -0
  766. package/llms/stitchkit.txt +260 -0
  767. package/llms/telegram.txt +30 -0
  768. package/llms/testing.txt +676 -0
  769. package/llms/tools-connections.txt +45 -0
  770. package/llms/tools-contract.txt +9 -0
  771. package/llms/tools-invoker.txt +9 -0
  772. package/llms/tools.2.txt +647 -0
  773. package/llms/tools.3.txt +288 -0
  774. package/llms/tools.txt +966 -0
  775. package/llms/tracking-server.txt +32 -0
  776. package/llms/tracking.txt +263 -0
  777. package/llms/upgrading-0.37.0-0.50.0.txt +947 -0
  778. package/llms/upgrading-0.53.0-0.67.0.txt +1174 -0
  779. package/llms/upgrading-0.68.0-0.94.0.txt +1159 -0
  780. package/llms/upgrading.txt +215 -0
  781. package/llms-full.txt +312 -77
  782. package/llms.txt +54 -5
  783. package/package.json +84 -83
  784. package/dist/agent-runtime/durability-contract.d.ts +0 -176
  785. package/dist/agent-runtime/durability-contract.d.ts.map +0 -1
  786. package/dist/agent-runtime/durability-json.d.ts +0 -3
  787. package/dist/agent-runtime/durability-json.d.ts.map +0 -1
  788. package/dist/agent-runtime/durability-ledger.d.ts +0 -16
  789. package/dist/agent-runtime/durability-ledger.d.ts.map +0 -1
  790. package/dist/agent-runtime/durability-scheduler.d.ts +0 -29
  791. package/dist/agent-runtime/durability-scheduler.d.ts.map +0 -1
  792. package/dist/agent-runtime/durability.d.ts +0 -14
  793. package/dist/agent-runtime/durability.d.ts.map +0 -1
  794. package/dist/agent-runtime/store-driver.d.ts +0 -814
  795. package/dist/agent-runtime/store-driver.d.ts.map +0 -1
  796. package/dist/agent-runtime-browser.d.ts +0 -5
  797. package/dist/agent-runtime-browser.d.ts.map +0 -1
  798. package/dist/agent-runtime-browser.js +0 -124
  799. package/dist/agent-runtime-coding-tools.d.ts +0 -2
  800. package/dist/agent-runtime-coding-tools.d.ts.map +0 -1
  801. package/dist/agent-runtime-coding-tools.js +0 -23
  802. package/dist/agent-runtime-harness.d.ts +0 -2
  803. package/dist/agent-runtime-harness.d.ts.map +0 -1
  804. package/dist/agent-runtime-harness.js +0 -729
  805. package/dist/agent-runtime-openrouter.d.ts +0 -29
  806. package/dist/agent-runtime-openrouter.d.ts.map +0 -1
  807. package/dist/agent-runtime-openrouter.js +0 -270
  808. package/dist/agent-runtime-sandbox.d.ts +0 -5
  809. package/dist/agent-runtime-sandbox.d.ts.map +0 -1
  810. package/dist/agent-runtime-sandbox.js +0 -798
  811. package/dist/agent-runtime-sqlite-bun.d.ts +0 -11
  812. package/dist/agent-runtime-sqlite-bun.d.ts.map +0 -1
  813. package/dist/agent-runtime-sqlite-bun.js +0 -42
  814. package/dist/agent-runtime-sqlite-node.d.ts +0 -11
  815. package/dist/agent-runtime-sqlite-node.d.ts.map +0 -1
  816. package/dist/agent-runtime-sqlite-node.js +0 -44
  817. package/dist/agent-runtime-testing.d.ts +0 -3
  818. package/dist/agent-runtime-testing.d.ts.map +0 -1
  819. package/dist/agent-runtime-testing.js +0 -156
  820. package/dist/agent-runtime.d.ts +0 -38
  821. package/dist/agent-runtime.d.ts.map +0 -1
  822. package/dist/agent-runtime.js +0 -2607
  823. package/dist/application/channel.d.ts.map +0 -1
  824. package/dist/application-diagnostic-journal.d.ts +0 -21
  825. package/dist/application-diagnostic-journal.d.ts.map +0 -1
  826. package/dist/application-diagnostic-journal.js +0 -632
  827. package/dist/application-grammy.d.ts +0 -2
  828. package/dist/application-grammy.d.ts.map +0 -1
  829. package/dist/application-grammy.js +0 -169
  830. package/dist/application-opentelemetry.d.ts +0 -2
  831. package/dist/application-opentelemetry.d.ts.map +0 -1
  832. package/dist/application-opentelemetry.js +0 -250
  833. package/dist/application-schemas.d.ts +0 -15
  834. package/dist/application-schemas.d.ts.map +0 -1
  835. package/dist/application-schemas.js +0 -27
  836. package/dist/application.d.ts +0 -22
  837. package/dist/application.d.ts.map +0 -1
  838. package/dist/application.js +0 -1977
  839. package/dist/cli.d.ts +0 -41
  840. package/dist/cli.d.ts.map +0 -1
  841. package/dist/cli.js +0 -753
  842. package/dist/contract/index.d.ts +0 -8
  843. package/dist/contract/index.d.ts.map +0 -1
  844. package/dist/contract/index.js +0 -55
  845. package/dist/declaration.d.ts.map +0 -1
  846. package/dist/declaration.js +0 -183
  847. package/dist/files.d.ts +0 -3
  848. package/dist/files.d.ts.map +0 -1
  849. package/dist/files.js +0 -15
  850. package/dist/geo.d.ts +0 -3
  851. package/dist/geo.d.ts.map +0 -1
  852. package/dist/geo.js +0 -245
  853. package/dist/google.d.ts.map +0 -1
  854. package/dist/google.js +0 -175
  855. package/dist/index-0a349c33.js +0 -470
  856. package/dist/index-0j3vcp5m.js +0 -28
  857. package/dist/index-2c2bjw3s.js +0 -51
  858. package/dist/index-2na0qrfn.js +0 -214
  859. package/dist/index-2qzskm8h.js +0 -63
  860. package/dist/index-3bmnp41g.js +0 -2169
  861. package/dist/index-3xwxfj4z.js +0 -334
  862. package/dist/index-4fpa9dy2.js +0 -51
  863. package/dist/index-6kyksz9y.js +0 -268
  864. package/dist/index-77fekveh.js +0 -44
  865. package/dist/index-7gnkny4z.js +0 -326
  866. package/dist/index-7zbps32p.js +0 -89
  867. package/dist/index-9f8ztey6.js +0 -588
  868. package/dist/index-a11g2kry.js +0 -866
  869. package/dist/index-a916km3r.js +0 -45
  870. package/dist/index-actkayzn.js +0 -367
  871. package/dist/index-bn2cjajt.js +0 -524
  872. package/dist/index-bx75zwt7.js +0 -63
  873. package/dist/index-cby4ar3v.js +0 -46
  874. package/dist/index-cnyk6te3.js +0 -77
  875. package/dist/index-cxqhvq21.js +0 -413
  876. package/dist/index-e0znv5gn.js +0 -176
  877. package/dist/index-e42wzzz5.js +0 -154
  878. package/dist/index-f477k430.js +0 -324
  879. package/dist/index-f9mb610r.js +0 -177
  880. package/dist/index-fadnxwna.js +0 -1046
  881. package/dist/index-fq77yfzc.js +0 -1303
  882. package/dist/index-h9etkkyk.js +0 -1126
  883. package/dist/index-hrbajay7.js +0 -1196
  884. package/dist/index-kw9t5ayn.js +0 -507
  885. package/dist/index-mzvgxp0n.js +0 -80
  886. package/dist/index-n0f51dfn.js +0 -3170
  887. package/dist/index-p13mwz16.js +0 -16
  888. package/dist/index-s8cnx02s.js +0 -90
  889. package/dist/index-sr93cwf9.js +0 -325
  890. package/dist/index-tmwcrptx.js +0 -85
  891. package/dist/index-v5573g1k.js +0 -142
  892. package/dist/index-vjpvjqpn.js +0 -86
  893. package/dist/index-vk3kq9sb.js +0 -3344
  894. package/dist/index-wc4x00bn.js +0 -103
  895. package/dist/index-wnfk50r0.js +0 -211
  896. package/dist/index-yewwh1w4.js +0 -647
  897. package/dist/index-yn8remb1.js +0 -290
  898. package/dist/index-ywd0y6m1.js +0 -394
  899. package/dist/index-zwkgfq1s.js +0 -345
  900. package/dist/index.d.ts +0 -14
  901. package/dist/index.d.ts.map +0 -1
  902. package/dist/index.js +0 -632
  903. package/dist/internal/errors.d.ts +0 -92
  904. package/dist/internal/errors.d.ts.map +0 -1
  905. package/dist/internal/observability-sink.d.ts +0 -81
  906. package/dist/internal/observability-sink.d.ts.map +0 -1
  907. package/dist/live.d.ts +0 -19
  908. package/dist/live.d.ts.map +0 -1
  909. package/dist/live.js +0 -282
  910. package/dist/logger.d.ts.map +0 -1
  911. package/dist/node.d.ts +0 -18
  912. package/dist/node.d.ts.map +0 -1
  913. package/dist/node.js +0 -303
  914. package/dist/oauth.d.ts +0 -57
  915. package/dist/oauth.d.ts.map +0 -1
  916. package/dist/oauth.js +0 -170
  917. package/dist/observability/index.d.ts +0 -19
  918. package/dist/observability/index.d.ts.map +0 -1
  919. package/dist/observability/index.js +0 -569
  920. package/dist/primitives.d.ts +0 -3
  921. package/dist/primitives.d.ts.map +0 -1
  922. package/dist/primitives.js +0 -754
  923. package/dist/react.d.ts +0 -5
  924. package/dist/react.d.ts.map +0 -1
  925. package/dist/react.js +0 -403
  926. package/dist/release.d.ts +0 -15
  927. package/dist/release.d.ts.map +0 -1
  928. package/dist/release.js +0 -196
  929. package/dist/remote.d.ts +0 -9
  930. package/dist/remote.d.ts.map +0 -1
  931. package/dist/remote.js +0 -88
  932. package/dist/retained.d.ts.map +0 -1
  933. package/dist/server/file-state-store.d.ts +0 -23
  934. package/dist/server/file-state-store.d.ts.map +0 -1
  935. package/dist/server/index.d.ts +0 -36
  936. package/dist/server/index.d.ts.map +0 -1
  937. package/dist/server/index.js +0 -1745
  938. package/dist/server/request.d.ts.map +0 -1
  939. package/dist/telegram.d.ts +0 -3
  940. package/dist/telegram.d.ts.map +0 -1
  941. package/dist/telegram.js +0 -224
  942. package/dist/testing/agent-store-conformance.d.ts +0 -40
  943. package/dist/testing/agent-store-conformance.d.ts.map +0 -1
  944. package/dist/testing.d.ts +0 -39
  945. package/dist/testing.d.ts.map +0 -1
  946. package/dist/testing.js +0 -2209
  947. package/dist/tool-invoker.d.ts +0 -9
  948. package/dist/tool-invoker.d.ts.map +0 -1
  949. package/dist/tool-invoker.js +0 -21
  950. package/dist/tools/async-operation-contract.d.ts.map +0 -1
  951. package/dist/tools/async-operation.d.ts +0 -332
  952. package/dist/tools/async-operation.d.ts.map +0 -1
  953. package/dist/tools/cli-args.d.ts +0 -143
  954. package/dist/tools/cli-args.d.ts.map +0 -1
  955. package/dist/tools/cli-checkpoint.d.ts +0 -24
  956. package/dist/tools/cli-checkpoint.d.ts.map +0 -1
  957. package/dist/tools/cli-command.d.ts +0 -70
  958. package/dist/tools/cli-command.d.ts.map +0 -1
  959. package/dist/tools/cli-format.d.ts +0 -49
  960. package/dist/tools/cli-format.d.ts.map +0 -1
  961. package/dist/tools/cli-installer.d.ts +0 -34
  962. package/dist/tools/cli-installer.d.ts.map +0 -1
  963. package/dist/tools/cli-invoke.d.ts +0 -143
  964. package/dist/tools/cli-invoke.d.ts.map +0 -1
  965. package/dist/tools/cli-manifest.d.ts +0 -80
  966. package/dist/tools/cli-manifest.d.ts.map +0 -1
  967. package/dist/tools/cli-policy.d.ts +0 -27
  968. package/dist/tools/cli-policy.d.ts.map +0 -1
  969. package/dist/tools/cli-profile.d.ts +0 -40
  970. package/dist/tools/cli-profile.d.ts.map +0 -1
  971. package/dist/tools/cli-signature.d.ts +0 -81
  972. package/dist/tools/cli-signature.d.ts.map +0 -1
  973. package/dist/tools/cli-stream.d.ts +0 -93
  974. package/dist/tools/cli-stream.d.ts.map +0 -1
  975. package/dist/tools/cli-update.d.ts +0 -126
  976. package/dist/tools/cli-update.d.ts.map +0 -1
  977. package/dist/tools/cli-view.d.ts +0 -12
  978. package/dist/tools/cli-view.d.ts.map +0 -1
  979. package/dist/tools/cli-wait.d.ts +0 -54
  980. package/dist/tools/cli-wait.d.ts.map +0 -1
  981. package/dist/tools/cli.d.ts +0 -94
  982. package/dist/tools/cli.d.ts.map +0 -1
  983. package/dist/tools/coerce.d.ts.map +0 -1
  984. package/dist/tools/connections/index.d.ts +0 -20
  985. package/dist/tools/connections/index.d.ts.map +0 -1
  986. package/dist/tools/connections/index.js +0 -1107
  987. package/dist/tools/define-download-tool.d.ts +0 -18
  988. package/dist/tools/define-download-tool.d.ts.map +0 -1
  989. package/dist/tools/define-upload-tool.d.ts +0 -16
  990. package/dist/tools/define-upload-tool.d.ts.map +0 -1
  991. package/dist/tools/define-view-file-tool.d.ts +0 -10
  992. package/dist/tools/define-view-file-tool.d.ts.map +0 -1
  993. package/dist/tools/define-wait-tool.d.ts +0 -22
  994. package/dist/tools/define-wait-tool.d.ts.map +0 -1
  995. package/dist/tools/download-core.d.ts +0 -20
  996. package/dist/tools/download-core.d.ts.map +0 -1
  997. package/dist/tools/flatten-join.d.ts.map +0 -1
  998. package/dist/tools/flatten.d.ts.map +0 -1
  999. package/dist/tools/json-schema-dialect.d.ts +0 -17
  1000. package/dist/tools/json-schema-dialect.d.ts.map +0 -1
  1001. package/dist/tools/json-schema.d.ts.map +0 -1
  1002. package/dist/tools/managed-file-error.d.ts +0 -6
  1003. package/dist/tools/managed-file-error.d.ts.map +0 -1
  1004. package/dist/tools/mcp-app.d.ts +0 -62
  1005. package/dist/tools/mcp-app.d.ts.map +0 -1
  1006. package/dist/tools/mcp-catalog.d.ts +0 -68
  1007. package/dist/tools/mcp-catalog.d.ts.map +0 -1
  1008. package/dist/tools/mcp-handler.d.ts +0 -46
  1009. package/dist/tools/mcp-handler.d.ts.map +0 -1
  1010. package/dist/tools/mcp-prepare.d.ts +0 -75
  1011. package/dist/tools/mcp-prepare.d.ts.map +0 -1
  1012. package/dist/tools/mcp-progress.d.ts +0 -46
  1013. package/dist/tools/mcp-progress.d.ts.map +0 -1
  1014. package/dist/tools/mcp-round-policy.d.ts +0 -33
  1015. package/dist/tools/mcp-round-policy.d.ts.map +0 -1
  1016. package/dist/tools/mcp-round.d.ts +0 -61
  1017. package/dist/tools/mcp-round.d.ts.map +0 -1
  1018. package/dist/tools/mcp-stdio-signals.d.ts +0 -33
  1019. package/dist/tools/mcp-stdio-signals.d.ts.map +0 -1
  1020. package/dist/tools/mcp-stdio.d.ts +0 -20
  1021. package/dist/tools/mcp-stdio.d.ts.map +0 -1
  1022. package/dist/tools/mcp-trace.d.ts +0 -12
  1023. package/dist/tools/mcp-trace.d.ts.map +0 -1
  1024. package/dist/tools/mcp.d.ts +0 -152
  1025. package/dist/tools/mcp.d.ts.map +0 -1
  1026. package/dist/tools/mount-download.d.ts +0 -41
  1027. package/dist/tools/mount-download.d.ts.map +0 -1
  1028. package/dist/tools/mount-upload.d.ts +0 -21
  1029. package/dist/tools/mount-upload.d.ts.map +0 -1
  1030. package/dist/tools/mount-wait.d.ts.map +0 -1
  1031. package/dist/tools/native-mcp.d.ts +0 -20
  1032. package/dist/tools/native-mcp.d.ts.map +0 -1
  1033. package/dist/tools/native-result.d.ts.map +0 -1
  1034. package/dist/tools/oauth-metadata.d.ts +0 -28
  1035. package/dist/tools/oauth-metadata.d.ts.map +0 -1
  1036. package/dist/tools/oauth-provider.d.ts +0 -184
  1037. package/dist/tools/oauth-provider.d.ts.map +0 -1
  1038. package/dist/tools/portable-formats.d.ts.map +0 -1
  1039. package/dist/tools/presentation.d.ts +0 -22
  1040. package/dist/tools/presentation.d.ts.map +0 -1
  1041. package/dist/tools/schema.d.ts.map +0 -1
  1042. package/dist/tools/untyped-properties.d.ts.map +0 -1
  1043. package/dist/tools/upload-core.d.ts +0 -4
  1044. package/dist/tools/upload-core.d.ts.map +0 -1
  1045. package/dist/tools/view-file-contract.d.ts.map +0 -1
  1046. package/dist/tools/view-file.d.ts +0 -62
  1047. package/dist/tools/view-file.d.ts.map +0 -1
  1048. package/dist/tools/wait-core.d.ts.map +0 -1
  1049. package/dist/tools-contract.d.ts +0 -29
  1050. package/dist/tools-contract.d.ts.map +0 -1
  1051. package/dist/tools-contract.js +0 -24
  1052. package/dist/tools.d.ts +0 -50
  1053. package/dist/tools.d.ts.map +0 -1
  1054. package/dist/tools.js +0 -2930
  1055. package/dist/tracking-server.d.ts +0 -15
  1056. package/dist/tracking-server.d.ts.map +0 -1
  1057. package/dist/tracking.d.ts +0 -24
  1058. package/dist/tracking.d.ts.map +0 -1
  1059. package/dist/tracking.js +0 -1092
  1060. package/dist/upgrade-cli.d.ts.map +0 -1
  1061. package/dist/upgrade-cli.js +0 -177
  1062. /package/dist/{retained.d.ts → browser/retained.d.ts} +0 -0
  1063. /package/dist/{declaration.d.ts → declaration/declaration.d.ts} +0 -0
  1064. /package/dist/{upgrade-cli.d.ts → entrypoints/bin/upgrade-cli.d.ts} +0 -0
  1065. /package/dist/{tracking-server.js → entrypoints/tracking/server.js} +0 -0
  1066. /package/dist/{google.d.ts → google/google.d.ts} +0 -0
  1067. /package/dist/{index-pq95qkbf.js → index-5jm36zv1.js} +0 -0
  1068. /package/dist/{application → internal}/channel.d.ts +0 -0
  1069. /package/dist/{logger.d.ts → internal/logger.d.ts} +0 -0
  1070. /package/dist/{server → internal}/request.d.ts +0 -0
  1071. /package/dist/{tools → json-schema}/json-schema.d.ts +0 -0
  1072. /package/dist/tools/{async-operation-contract.d.ts → operations/async-operation-contract.d.ts} +0 -0
  1073. /package/dist/tools/{mount-wait.d.ts → operations/mount-wait.d.ts} +0 -0
  1074. /package/dist/tools/{wait-core.d.ts → operations/wait-core.d.ts} +0 -0
  1075. /package/dist/tools/{coerce.d.ts → schema/coerce.d.ts} +0 -0
  1076. /package/dist/tools/{flatten-join.d.ts → schema/flatten-join.d.ts} +0 -0
  1077. /package/dist/tools/{flatten.d.ts → schema/flatten.d.ts} +0 -0
  1078. /package/dist/tools/{portable-formats.d.ts → schema/portable-formats.d.ts} +0 -0
  1079. /package/dist/tools/{schema.d.ts → schema/schema.d.ts} +0 -0
  1080. /package/dist/tools/{untyped-properties.d.ts → schema/untyped-properties.d.ts} +0 -0
  1081. /package/dist/tools/{native-result.d.ts → transfer/native-result.d.ts} +0 -0
  1082. /package/dist/tools/{view-file-contract.d.ts → transfer/view-file-contract.d.ts} +0 -0
@@ -0,0 +1,3009 @@
1
+ import {
2
+ ManagedFileError
3
+ } from "../index-paz6sgdp.js";
4
+ import {
5
+ signJwt,
6
+ verifyPkce
7
+ } from "../index-e01r054k.js";
8
+ import"../index-hr4tzbwq.js";
9
+ import {
10
+ DEFAULT_CORS_ALLOW_HEADERS,
11
+ DEFAULT_PROCESS_SIGNALS,
12
+ contractOnlyService,
13
+ defaultSignalSource,
14
+ guardSignalCallback,
15
+ mediaTypeEssence,
16
+ reportSignalError
17
+ } from "../index-2gxzjvyr.js";
18
+ import"../index-2bxbyab0.js";
19
+ import {
20
+ redact
21
+ } from "../index-yw4fzmdz.js";
22
+ import {
23
+ buildToolManifest,
24
+ describeToolCatalog,
25
+ mountAgent
26
+ } from "../index-863ea9jb.js";
27
+ import {
28
+ AgentToolError,
29
+ EffectUnresolvedError,
30
+ createLocalStepDurability,
31
+ isAgentToolError
32
+ } from "../index-79z7m7dt.js";
33
+ import"../index-rxfy4cq7.js";
34
+ import {
35
+ ALL_TRANSPORTS,
36
+ TOOL_TRANSPORTS,
37
+ defineContract
38
+ } from "../index-k30h66yd.js";
39
+ import"../index-4gcnakhx.js";
40
+ import {
41
+ ManagedFilePathSchema,
42
+ ManagedFileRefSchema
43
+ } from "../index-6k1937bx.js";
44
+ import {
45
+ AsyncOperationCancelResultSchema,
46
+ McpAnnotationsSchema,
47
+ McpMediaContentSchema,
48
+ ViewFileErrorSchema,
49
+ ViewFileInputSchema,
50
+ ViewFileOutputSchema,
51
+ createAsyncOperationSnapshotSchema
52
+ } from "../index-m9zn6cpq.js";
53
+ import {
54
+ createToolInvoker
55
+ } from "../index-p9sh0xx4.js";
56
+ import {
57
+ WaitTimeoutError,
58
+ createCli,
59
+ fetchGuarded,
60
+ fetchPinnedDocument,
61
+ readCapped,
62
+ runWaitOperation
63
+ } from "../index-t9rhjr9f.js";
64
+ import"../index-sbdmyz75.js";
65
+ import {
66
+ collectToolSurface
67
+ } from "../index-hmp4800j.js";
68
+ import {
69
+ argumentsDigest
70
+ } from "../index-0b1ess5e.js";
71
+ import {
72
+ collectTools,
73
+ createToolRunner,
74
+ formatToolError
75
+ } from "../index-khtgb21r.js";
76
+ import {
77
+ ToolExecutionControlError,
78
+ isToolExecutionControlError,
79
+ parseToolCallArguments,
80
+ toolResultFromError
81
+ } from "../index-55hkhm67.js";
82
+ import {
83
+ getRequestContext,
84
+ getTraceId,
85
+ runWithRequestContext
86
+ } from "../index-zfrhfn82.js";
87
+ import"../index-35mh5bhj.js";
88
+ import {
89
+ resolvePropagationContext
90
+ } from "../index-zcgf3gqf.js";
91
+ import {
92
+ coerceJsonArgs
93
+ } from "../index-1zbbzgfh.js";
94
+ import {
95
+ createRuntimeToolFactory,
96
+ defineRuntimeTool
97
+ } from "../index-xw3s75nj.js";
98
+ import {
99
+ PORTABLE_JSON_SCHEMA_FORMATS,
100
+ assertToolName,
101
+ assertUniqueToolName,
102
+ findNonPortableFormats,
103
+ findUntypedProperties,
104
+ flattenToolJsonSchema,
105
+ prepareProjectedMcpTools,
106
+ presentationMetadata,
107
+ staticInputRounds,
108
+ toolSurfaceOutputSchema,
109
+ validateMcpRoundPolicy,
110
+ validateResolvedInputRounds
111
+ } from "../index-np4m8hd3.js";
112
+ import {
113
+ toJsonSchema
114
+ } from "../index-eqqvgdb3.js";
115
+ import {
116
+ normalizeError
117
+ } from "../index-znfs20ss.js";
118
+ import"../index-p5r7qpdd.js";
119
+ import {
120
+ AppError,
121
+ STITCH_ERROR_STATUS
122
+ } from "../index-2vtcmrj9.js";
123
+ import {
124
+ compareCodeUnits,
125
+ serializeCanonicalJson
126
+ } from "../index-k5hsfc3j.js";
127
+ import"../index-kzfs85xp.js";
128
+ import {
129
+ isRecord
130
+ } from "../index-hffjpmq9.js";
131
+ // src/server/oauth/cimd.ts
132
+ import { z } from "zod";
133
+ function isPlainDisplayCharacter(character) {
134
+ const codePoint = character.codePointAt(0);
135
+ return codePoint !== undefined && codePoint >= 32 && codePoint !== 127 && character !== "<" && character !== ">";
136
+ }
137
+ var CimdClientMetadataSchema = z.object({
138
+ client_id: z.url(),
139
+ redirect_uris: z.array(z.url()).min(1),
140
+ client_name: z.string().trim().min(1).max(200).refine((value) => Array.from(value).every(isPlainDisplayCharacter), {
141
+ message: "client_name must be plain display text"
142
+ }),
143
+ token_endpoint_auth_method: z.literal("none"),
144
+ application_type: z.enum(["native", "web"]).optional()
145
+ });
146
+ function createSecureClientMetadataFetcher(policy = {}) {
147
+ assertPositiveInteger("cimd.maxBytes", policy.maxBytes ?? DEFAULT_CIMD_MAX_BYTES);
148
+ assertPositiveNumber("cimd.timeoutMs", policy.timeoutMs ?? DEFAULT_CIMD_TIMEOUT_MS);
149
+ assertNonNegativeInteger("cimd.maxRedirects", policy.maxRedirects ?? 3);
150
+ return {
151
+ fetch: (url, headers) => fetchPinnedDocument(url, {
152
+ maxBytes: policy.maxBytes ?? DEFAULT_CIMD_MAX_BYTES,
153
+ timeoutMs: policy.timeoutMs ?? DEFAULT_CIMD_TIMEOUT_MS,
154
+ maxRedirects: policy.maxRedirects ?? 3,
155
+ headers,
156
+ requireHttps: true
157
+ })
158
+ };
159
+ }
160
+ var DEFAULT_CIMD_MAX_BYTES = 64 * 1024;
161
+ var DEFAULT_CIMD_TIMEOUT_MS = 5000;
162
+ function assertPositiveInteger(name, value) {
163
+ if (!Number.isInteger(value) || value < 1)
164
+ throw new Error(`${name} must be a positive integer`);
165
+ }
166
+ function assertNonNegativeInteger(name, value) {
167
+ if (!Number.isInteger(value) || value < 0) {
168
+ throw new Error(`${name} must be a non-negative integer`);
169
+ }
170
+ }
171
+ function assertPositiveNumber(name, value) {
172
+ if (!Number.isFinite(value) || value <= 0)
173
+ throw new Error(`${name} must be positive`);
174
+ }
175
+ function absoluteClientUrl(clientId) {
176
+ try {
177
+ return new URL(clientId);
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+ function assertCimdClientId(clientId) {
183
+ const url = new URL(clientId);
184
+ if (url.protocol !== "https:")
185
+ throw new Error("CIMD client_id must use https");
186
+ if (url.username || url.password)
187
+ throw new Error("CIMD client_id cannot contain credentials");
188
+ if (url.hash)
189
+ throw new Error("CIMD client_id cannot contain a fragment");
190
+ if (url.search)
191
+ throw new Error("CIMD client_id cannot contain a query");
192
+ if (url.toString() !== clientId) {
193
+ throw new Error("CIMD client_id must be an exact canonical URL");
194
+ }
195
+ return url;
196
+ }
197
+ function parseAgeSeconds(headers) {
198
+ const raw = headers.get("age");
199
+ if (raw === null)
200
+ return 0;
201
+ const first = raw.split(",")[0]?.trim() ?? "";
202
+ return /^\d+$/.test(first) ? Number(first) : 0;
203
+ }
204
+ function responseFreshness(headers, policy, now) {
205
+ const maxTtl = policy.maxTtlMs ?? 3600000;
206
+ const cacheControl = headers.get("cache-control") ?? "";
207
+ if (/(?:^|,)\s*no-store\s*(?:,|$)/i.test(cacheControl)) {
208
+ return { freshnessMs: 0, store: false };
209
+ }
210
+ if (/(?:^|,)\s*no-cache\s*(?:,|$)/i.test(cacheControl)) {
211
+ return { freshnessMs: 0, store: true };
212
+ }
213
+ const maxAge = cacheControl.match(/(?:^|,)\s*max-age=([^,\s]*)/i)?.[1];
214
+ if (maxAge !== undefined) {
215
+ if (!/^\d+$/.test(maxAge))
216
+ return { freshnessMs: 0, store: true };
217
+ const age = parseAgeSeconds(headers);
218
+ return {
219
+ freshnessMs: Math.max(0, Math.min(maxTtl, (Number(maxAge) - age) * 1000)),
220
+ store: true
221
+ };
222
+ }
223
+ const expires = headers.get("expires");
224
+ if (expires !== null) {
225
+ const expiresAt = Date.parse(expires);
226
+ if (!Number.isFinite(expiresAt))
227
+ return { freshnessMs: 0, store: true };
228
+ const dateAt = Date.parse(headers.get("date") ?? "");
229
+ const ageMs = parseAgeSeconds(headers) * 1000;
230
+ const lifetime = Number.isFinite(dateAt) ? expiresAt - dateAt : expiresAt - now;
231
+ return {
232
+ freshnessMs: Math.max(0, Math.min(maxTtl, lifetime - ageMs)),
233
+ store: true
234
+ };
235
+ }
236
+ return { freshnessMs: Math.min(maxTtl, policy.defaultTtlMs ?? 300000), store: true };
237
+ }
238
+ function toRegisteredClient(metadata) {
239
+ return {
240
+ clientId: metadata.client_id,
241
+ redirectUris: metadata.redirect_uris,
242
+ ...metadata.client_name !== undefined && { clientName: metadata.client_name },
243
+ ...metadata.application_type !== undefined && {
244
+ applicationType: metadata.application_type
245
+ }
246
+ };
247
+ }
248
+ function isJsonContentType(value) {
249
+ const mediaType = value.split(";", 1)[0]?.trim().toLowerCase();
250
+ return mediaType === "application/json" || mediaType?.endsWith("+json") === true;
251
+ }
252
+ function createCimdResolver(options) {
253
+ const policy = options.cache ?? {};
254
+ const now = options.now ?? Date.now;
255
+ const positives = new Map;
256
+ const negatives = new Map;
257
+ const inflight = new Map;
258
+ const maxEntries = policy.maxEntries ?? 256;
259
+ const maxResolutions = policy.maxResolutions ?? 120;
260
+ const maxResolutionsPerClient = policy.maxResolutionsPerClient ?? 10;
261
+ const resolutionWindowMs = policy.resolutionWindowMs ?? 60000;
262
+ let resolutionWindowStartedAt = now();
263
+ let resolutionsInWindow = 0;
264
+ const clientWindows = new Map;
265
+ const CLIENT_WINDOW_CAP = 4096;
266
+ assertPositiveInteger("cimd.cache.maxEntries", maxEntries);
267
+ assertPositiveInteger("cimd.cache.maxResolutions", maxResolutions);
268
+ assertPositiveInteger("cimd.cache.maxResolutionsPerClient", maxResolutionsPerClient);
269
+ assertPositiveInteger("cimd.cache.resolutionWindowMs", resolutionWindowMs);
270
+ assertNonNegativeInteger("cimd.cache.defaultTtlMs", policy.defaultTtlMs ?? 300000);
271
+ assertNonNegativeInteger("cimd.cache.maxTtlMs", policy.maxTtlMs ?? 3600000);
272
+ assertNonNegativeInteger("cimd.cache.negativeTtlMs", policy.negativeTtlMs ?? 1e4);
273
+ const emit = (event) => {
274
+ try {
275
+ options.onCacheEvent?.(event);
276
+ } catch {}
277
+ };
278
+ const readCache = (key) => positives.get(key) ?? negatives.get(key);
279
+ const trimOldest = (pool) => {
280
+ while (pool.size > maxEntries) {
281
+ const oldest = pool.keys().next().value;
282
+ if (oldest === undefined)
283
+ break;
284
+ pool.delete(oldest);
285
+ }
286
+ };
287
+ const touch = (key, value) => {
288
+ if (value.ok) {
289
+ negatives.delete(key);
290
+ positives.delete(key);
291
+ positives.set(key, value);
292
+ trimOldest(positives);
293
+ } else {
294
+ positives.delete(key);
295
+ negatives.delete(key);
296
+ negatives.set(key, value);
297
+ trimOldest(negatives);
298
+ }
299
+ };
300
+ const dropCache = (key) => {
301
+ positives.delete(key);
302
+ negatives.delete(key);
303
+ };
304
+ const resolveOne = async (clientId) => {
305
+ const url = assertCimdClientId(clientId);
306
+ const cached = readCache(clientId);
307
+ if (cached && cached.expiresAt > now()) {
308
+ touch(clientId, cached);
309
+ if (cached.ok) {
310
+ emit({ clientId, status: "hit", freshnessMs: cached.expiresAt - now() });
311
+ return cached.client;
312
+ }
313
+ emit({ clientId, status: "negative", freshnessMs: cached.expiresAt - now() });
314
+ throw new Error(cached.message);
315
+ }
316
+ emit({ clientId, status: "miss" });
317
+ const currentTime = now();
318
+ if (currentTime - resolutionWindowStartedAt >= resolutionWindowMs) {
319
+ resolutionWindowStartedAt = currentTime;
320
+ resolutionsInWindow = 0;
321
+ }
322
+ let clientWindow = clientWindows.get(clientId);
323
+ if (!clientWindow || currentTime - clientWindow.startedAt >= resolutionWindowMs) {
324
+ clientWindow = { startedAt: currentTime, count: 0 };
325
+ clientWindows.delete(clientId);
326
+ clientWindows.set(clientId, clientWindow);
327
+ while (clientWindows.size > CLIENT_WINDOW_CAP) {
328
+ const oldest = clientWindows.keys().next().value;
329
+ if (oldest === undefined)
330
+ break;
331
+ clientWindows.delete(oldest);
332
+ }
333
+ }
334
+ if (clientWindow.count >= maxResolutionsPerClient) {
335
+ throw new Error("CIMD metadata resolution rate limit exceeded for this client_id");
336
+ }
337
+ if (resolutionsInWindow >= maxResolutions) {
338
+ throw new Error("CIMD metadata resolution rate limit exceeded");
339
+ }
340
+ clientWindow.count += 1;
341
+ resolutionsInWindow += 1;
342
+ const conditionalHeaders = {};
343
+ if (cached?.ok && cached.etag)
344
+ conditionalHeaders["if-none-match"] = cached.etag;
345
+ if (cached?.ok && cached.lastModified) {
346
+ conditionalHeaders["if-modified-since"] = cached.lastModified;
347
+ }
348
+ try {
349
+ const response = await options.fetcher.fetch(url, conditionalHeaders);
350
+ const freshness = responseFreshness(response.headers, policy, now());
351
+ if (response.status === 304 && cached?.ok) {
352
+ const refreshed = {
353
+ ...cached,
354
+ expiresAt: now() + freshness.freshnessMs
355
+ };
356
+ if (freshness.store)
357
+ touch(clientId, refreshed);
358
+ else
359
+ dropCache(clientId);
360
+ emit({ clientId, status: "revalidated", freshnessMs: freshness.freshnessMs });
361
+ return refreshed.client;
362
+ }
363
+ if (response.status !== 200) {
364
+ throw new Error(`CIMD endpoint returned HTTP ${response.status}`);
365
+ }
366
+ const contentType = response.headers.get("content-type") ?? "";
367
+ if (!isJsonContentType(contentType)) {
368
+ throw new Error("CIMD endpoint must return a JSON media type");
369
+ }
370
+ const decoded = JSON.parse(new TextDecoder().decode(response.body));
371
+ const metadata = CimdClientMetadataSchema.parse(decoded);
372
+ if (metadata.client_id !== clientId) {
373
+ throw new Error("CIMD client_id does not exactly match the requested URL");
374
+ }
375
+ if (!metadata.redirect_uris.every((uri) => isRegistrableRedirectUri(uri, metadata.application_type))) {
376
+ throw new Error("CIMD redirect_uris contains a URI forbidden for the application type");
377
+ }
378
+ const client = toRegisteredClient(metadata);
379
+ if (freshness.store && Number.isFinite(freshness.freshnessMs)) {
380
+ touch(clientId, {
381
+ ok: true,
382
+ client,
383
+ expiresAt: now() + freshness.freshnessMs,
384
+ ...response.headers.get("etag") !== null && {
385
+ etag: response.headers.get("etag") ?? undefined
386
+ },
387
+ ...response.headers.get("last-modified") !== null && {
388
+ lastModified: response.headers.get("last-modified") ?? undefined
389
+ }
390
+ });
391
+ } else {
392
+ dropCache(clientId);
393
+ }
394
+ return client;
395
+ } catch (error) {
396
+ const message = error instanceof Error ? error.message : "CIMD metadata resolution failed";
397
+ touch(clientId, {
398
+ ok: false,
399
+ message,
400
+ expiresAt: now() + (policy.negativeTtlMs ?? 1e4)
401
+ });
402
+ throw error;
403
+ }
404
+ };
405
+ return async (clientId) => {
406
+ const pending = inflight.get(clientId);
407
+ if (pending)
408
+ return pending;
409
+ const created = resolveOne(clientId).finally(() => inflight.delete(clientId));
410
+ inflight.set(clientId, created);
411
+ return created;
412
+ };
413
+ }
414
+ function isRegistrableRedirectUri(value, applicationType) {
415
+ try {
416
+ const url = new URL(value);
417
+ if (url.username || url.password || url.hash)
418
+ return false;
419
+ if (url.protocol === "https:")
420
+ return true;
421
+ if (url.protocol !== "http:")
422
+ return false;
423
+ if (applicationType === "web")
424
+ return false;
425
+ const host = url.hostname.replace(/^\[|\]$/g, "");
426
+ return host === "127.0.0.1" || host === "::1" || host === "localhost";
427
+ } catch {
428
+ return false;
429
+ }
430
+ }
431
+ function isLoopbackRedirectUri(value) {
432
+ try {
433
+ const url = new URL(value);
434
+ if (url.protocol !== "http:")
435
+ return false;
436
+ const host = url.hostname.replace(/^\[|\]$/g, "");
437
+ return host === "127.0.0.1" || host === "::1" || host === "localhost";
438
+ } catch {
439
+ return false;
440
+ }
441
+ }
442
+ // src/server/oauth/metadata.ts
443
+ var PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";
444
+ function metadataPath(resource) {
445
+ const { pathname } = new URL(resource);
446
+ return pathname === "/" ? PROTECTED_RESOURCE_PATH : `${PROTECTED_RESOURCE_PATH}${pathname}`;
447
+ }
448
+ function protectedResourceMetadataUrl(resource) {
449
+ return `${new URL(resource).origin}${metadataPath(resource)}`;
450
+ }
451
+ function wwwAuthenticateHeader(resource) {
452
+ return `Bearer resource_metadata="${protectedResourceMetadataUrl(resource)}"`;
453
+ }
454
+ var PUBLIC_CORS = {
455
+ "Access-Control-Allow-Origin": "*",
456
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
457
+ "Access-Control-Allow-Headers": DEFAULT_CORS_ALLOW_HEADERS
458
+ };
459
+ function oauthProtectedResourceRoute(config) {
460
+ const body = JSON.stringify({
461
+ resource: config.resource,
462
+ authorization_servers: config.authorizationServers,
463
+ ...config.scopesSupported && { scopes_supported: config.scopesSupported },
464
+ bearer_methods_supported: ["header"]
465
+ });
466
+ return {
467
+ method: "ALL",
468
+ path: metadataPath(config.resource),
469
+ handler: (req) => {
470
+ if (req.method === "OPTIONS")
471
+ return new Response(null, { status: 204, headers: PUBLIC_CORS });
472
+ if (req.method !== "GET")
473
+ return new Response("Method Not Allowed", { status: 405 });
474
+ return new Response(body, {
475
+ status: 200,
476
+ headers: { "Content-Type": "application/json", ...PUBLIC_CORS }
477
+ });
478
+ }
479
+ };
480
+ }
481
+ // src/server/oauth/endpoints.ts
482
+ import { randomUUID } from "node:crypto";
483
+ var PUBLIC_CORS2 = {
484
+ "Access-Control-Allow-Origin": "*",
485
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
486
+ "Access-Control-Allow-Headers": DEFAULT_CORS_ALLOW_HEADERS
487
+ };
488
+ var AS_METADATA_PATH = "/.well-known/oauth-authorization-server";
489
+ var AUTH_CODE_TTL_MS = 60000;
490
+ function safeClientName(value) {
491
+ if (value === undefined)
492
+ return;
493
+ const safe = Array.from(value).filter(isPlainDisplayCharacter).join("").trim().slice(0, 200);
494
+ return safe || undefined;
495
+ }
496
+ function parseScopes(value) {
497
+ if (!value)
498
+ return [];
499
+ return [...new Set(value.split(/\s+/u).filter(Boolean))];
500
+ }
501
+ function json(body, status = 200, extraHeaders) {
502
+ return new Response(JSON.stringify(body), {
503
+ status,
504
+ headers: { "Content-Type": "application/json", ...PUBLIC_CORS2, ...extraHeaders }
505
+ });
506
+ }
507
+ function oauthError(error, description, status = 400) {
508
+ return json({ error, error_description: description }, status);
509
+ }
510
+ function redirectWith(uri, params) {
511
+ const url = new URL(uri);
512
+ for (const [key, value] of Object.entries(params))
513
+ url.searchParams.set(key, value);
514
+ return new Response(null, { status: 302, headers: { Location: url.toString() } });
515
+ }
516
+ async function readForm(req) {
517
+ const contentType = req.headers.get("content-type") ?? "";
518
+ if (contentType.includes("application/json")) {
519
+ const body = await req.json().catch(() => null);
520
+ const params = new URLSearchParams;
521
+ if (isRecord(body)) {
522
+ for (const [key, value] of Object.entries(body)) {
523
+ if (typeof value === "string")
524
+ params.set(key, value);
525
+ }
526
+ }
527
+ return params;
528
+ }
529
+ return new URLSearchParams(await req.text());
530
+ }
531
+ function metadataRoute(ctx) {
532
+ const { config } = ctx;
533
+ return {
534
+ method: "ALL",
535
+ path: AS_METADATA_PATH,
536
+ handler: (req) => {
537
+ if (req.method === "OPTIONS")
538
+ return new Response(null, { status: 204, headers: PUBLIC_CORS2 });
539
+ return json({
540
+ issuer: config.issuer,
541
+ authorization_endpoint: `${config.issuer}${ctx.paths.authorize}`,
542
+ token_endpoint: `${config.issuer}${ctx.paths.token}`,
543
+ ...ctx.dcrRegistry !== undefined && {
544
+ registration_endpoint: `${config.issuer}${ctx.paths.register}`
545
+ },
546
+ response_types_supported: ["code"],
547
+ grant_types_supported: config.refreshTokens ? ["authorization_code", "refresh_token"] : ["authorization_code"],
548
+ code_challenge_methods_supported: ["S256"],
549
+ token_endpoint_auth_methods_supported: ["none"],
550
+ ...ctx.cimdEnabled && { client_id_metadata_document_supported: true },
551
+ authorization_response_iss_parameter_supported: true,
552
+ ...config.scopesSupported && { scopes_supported: config.scopesSupported }
553
+ });
554
+ }
555
+ };
556
+ }
557
+ function registerRoute(ctx) {
558
+ const { config } = ctx;
559
+ return {
560
+ method: "ALL",
561
+ path: ctx.paths.register,
562
+ handler: async (req) => {
563
+ if (req.method === "OPTIONS")
564
+ return new Response(null, { status: 204, headers: PUBLIC_CORS2 });
565
+ if (req.method !== "POST")
566
+ return oauthError("invalid_request", "POST required", 405);
567
+ const meta = await req.json().catch(() => null);
568
+ if (!isRecord(meta)) {
569
+ return oauthError("invalid_client_metadata", "Body must be a JSON object");
570
+ }
571
+ const rawAppType = meta.application_type;
572
+ if (rawAppType !== undefined && rawAppType !== "native" && rawAppType !== "web") {
573
+ return oauthError("invalid_client_metadata", "application_type must be 'native' or 'web'");
574
+ }
575
+ const applicationType = rawAppType;
576
+ const redirectUris = meta.redirect_uris;
577
+ const tokenEndpointAuthMethod = meta.token_endpoint_auth_method ?? "none";
578
+ if (tokenEndpointAuthMethod !== "none") {
579
+ return oauthError("invalid_client_metadata", 'Only public clients with token_endpoint_auth_method "none" are supported');
580
+ }
581
+ if (!Array.isArray(redirectUris) || redirectUris.length === 0 || !redirectUris.every((u) => typeof u === "string" && isRegistrableRedirectUri(u, applicationType))) {
582
+ return oauthError("invalid_redirect_uri", applicationType === "web" ? "redirect_uris must be a non-empty array of absolute https URLs (a web client cannot register an http loopback URI)" : "redirect_uris must be a non-empty array of absolute https URLs (http is allowed only on a loopback host)");
583
+ }
584
+ if (!ctx.dcrRegistry)
585
+ throw new Error("DCR route mounted without a DCR registry");
586
+ const client = await ctx.dcrRegistry.register({
587
+ redirectUris,
588
+ clientName: typeof meta.client_name === "string" ? meta.client_name : undefined,
589
+ tokenEndpointAuthMethod,
590
+ ...applicationType && { applicationType }
591
+ });
592
+ return json({
593
+ client_id: client.clientId,
594
+ redirect_uris: client.redirectUris,
595
+ token_endpoint_auth_method: "none",
596
+ grant_types: config.refreshTokens ? ["authorization_code", "refresh_token"] : ["authorization_code"],
597
+ response_types: ["code"],
598
+ ...client.clientName && { client_name: client.clientName },
599
+ ...client.applicationType && { application_type: client.applicationType }
600
+ }, 201);
601
+ }
602
+ };
603
+ }
604
+ function authorizeRoute(ctx) {
605
+ const { config } = ctx;
606
+ return {
607
+ method: "ALL",
608
+ path: ctx.paths.authorize,
609
+ handler: async (req) => {
610
+ if (req.method === "OPTIONS")
611
+ return new Response(null, { status: 204, headers: PUBLIC_CORS2 });
612
+ const url = new URL(req.url);
613
+ const p = url.searchParams;
614
+ const clientId = p.get("client_id");
615
+ const redirectUri = p.get("redirect_uri");
616
+ const responseType = p.get("response_type");
617
+ const codeChallenge = p.get("code_challenge");
618
+ const codeChallengeMethod = p.get("code_challenge_method") ?? "S256";
619
+ const resource = p.get("resource");
620
+ const scope = p.get("scope") ?? undefined;
621
+ const state = p.get("state") ?? undefined;
622
+ if (!clientId || !redirectUri) {
623
+ return oauthError("invalid_request", "client_id and redirect_uri are required");
624
+ }
625
+ const client = await ctx.resolveClient(clientId);
626
+ if (!client)
627
+ return oauthError("invalid_client", "Unknown client_id", 401);
628
+ if (!client.redirectUris.includes(redirectUri)) {
629
+ return oauthError("invalid_request", "redirect_uri does not match a registered URI");
630
+ }
631
+ if (responseType !== "code") {
632
+ return ctx.redirectToClient(redirectUri, {
633
+ error: "unsupported_response_type",
634
+ ...state && { state }
635
+ });
636
+ }
637
+ if (!codeChallenge || codeChallengeMethod !== "S256") {
638
+ return ctx.redirectToClient(redirectUri, {
639
+ error: "invalid_request",
640
+ error_description: "PKCE S256 code_challenge is required",
641
+ ...state && { state }
642
+ });
643
+ }
644
+ if (!resource) {
645
+ return ctx.redirectToClient(redirectUri, {
646
+ error: "invalid_target",
647
+ error_description: "resource parameter is required",
648
+ ...state && { state }
649
+ });
650
+ }
651
+ if (resource !== config.resource) {
652
+ return ctx.redirectToClient(redirectUri, {
653
+ error: "invalid_target",
654
+ error_description: "resource is not served by this authorization server",
655
+ ...state && { state }
656
+ });
657
+ }
658
+ const requestedScopes = parseScopes(scope);
659
+ const supportedScopes = new Set(config.scopesSupported ?? []);
660
+ if (config.scopesSupported && requestedScopes.some((requestedScope2) => !supportedScopes.has(requestedScope2))) {
661
+ return ctx.redirectToClient(redirectUri, {
662
+ error: "invalid_scope",
663
+ error_description: "One or more requested scopes are not supported",
664
+ ...state && { state }
665
+ });
666
+ }
667
+ const requestedScope = requestedScopes.length > 0 ? requestedScopes.join(" ") : undefined;
668
+ const authRequest = {
669
+ clientId,
670
+ redirectUri,
671
+ scope: requestedScope,
672
+ resource,
673
+ state,
674
+ isLoopbackRedirect: isLoopbackRedirectUri(redirectUri),
675
+ ...safeClientName(client.clientName) !== undefined && {
676
+ clientName: safeClientName(client.clientName)
677
+ },
678
+ ...client.applicationType !== undefined && {
679
+ applicationType: client.applicationType
680
+ },
681
+ ...absoluteClientUrl(clientId)?.protocol === "https:" && {
682
+ clientOrigin: new URL(clientId).origin
683
+ }
684
+ };
685
+ const result = await config.authorizeUser(req, authRequest);
686
+ if (result instanceof Response)
687
+ return result;
688
+ if (!Array.isArray(result.approvedScopes) || !result.approvedScopes.every((scope2) => typeof scope2 === "string")) {
689
+ throw new Error("authorizeUser must return approvedScopes as an array of strings");
690
+ }
691
+ const approvedScopes = [...new Set(result.approvedScopes)];
692
+ if (approvedScopes.some((approvedScope2) => !requestedScopes.includes(approvedScope2) || config.scopesSupported !== undefined && !supportedScopes.has(approvedScope2))) {
693
+ throw new Error("authorizeUser approvedScopes must be a subset of requested scopes");
694
+ }
695
+ const approvedScope = approvedScopes.length > 0 ? approvedScopes.join(" ") : undefined;
696
+ const code = randomUUID();
697
+ await config.codes.save(code, {
698
+ clientId,
699
+ redirectUri,
700
+ codeChallenge,
701
+ codeChallengeMethod: "S256",
702
+ resource,
703
+ scope: approvedScope,
704
+ userId: result.userId,
705
+ expiresAt: Date.now() + AUTH_CODE_TTL_MS
706
+ });
707
+ return ctx.redirectToClient(redirectUri, { code, ...state && { state } });
708
+ }
709
+ };
710
+ }
711
+ function tokenRoute(ctx) {
712
+ const { config } = ctx;
713
+ return {
714
+ method: "ALL",
715
+ path: ctx.paths.token,
716
+ handler: async (req) => {
717
+ if (req.method === "OPTIONS")
718
+ return new Response(null, { status: 204, headers: PUBLIC_CORS2 });
719
+ if (req.method !== "POST")
720
+ return oauthError("invalid_request", "POST required", 405);
721
+ const form = await readForm(req);
722
+ const grantType = form.get("grant_type");
723
+ if (grantType === "authorization_code") {
724
+ const code = form.get("code");
725
+ const verifier = form.get("code_verifier");
726
+ const redirectUri = form.get("redirect_uri");
727
+ const clientId = form.get("client_id");
728
+ if (!code || !verifier || !redirectUri || !clientId) {
729
+ return oauthError("invalid_request", "code, code_verifier, redirect_uri, client_id required");
730
+ }
731
+ const data = await config.codes.take(code);
732
+ if (!data)
733
+ return oauthError("invalid_grant", "Unknown or used authorization code");
734
+ if (data.expiresAt < Date.now())
735
+ return oauthError("invalid_grant", "Authorization code expired");
736
+ if (data.clientId !== clientId)
737
+ return oauthError("invalid_grant", "client_id mismatch");
738
+ if (data.redirectUri !== redirectUri)
739
+ return oauthError("invalid_grant", "redirect_uri mismatch");
740
+ if (!await verifyPkce(verifier, data.codeChallenge)) {
741
+ return oauthError("invalid_grant", "PKCE verification failed");
742
+ }
743
+ const accessToken = await ctx.issueAccessToken(data.userId, data.resource, data.clientId, data.scope);
744
+ let refreshToken;
745
+ if (config.refreshTokens) {
746
+ refreshToken = randomUUID();
747
+ await config.refreshTokens.save(refreshToken, {
748
+ clientId: data.clientId,
749
+ resource: data.resource,
750
+ scope: data.scope,
751
+ userId: data.userId
752
+ });
753
+ }
754
+ return json({
755
+ access_token: accessToken,
756
+ token_type: "Bearer",
757
+ expires_in: ctx.ttl,
758
+ ...data.scope && { scope: data.scope },
759
+ ...refreshToken && { refresh_token: refreshToken }
760
+ });
761
+ }
762
+ if (grantType === "refresh_token") {
763
+ if (!config.refreshTokens) {
764
+ return oauthError("unsupported_grant_type", "refresh_token grant is not enabled");
765
+ }
766
+ const token = form.get("refresh_token");
767
+ const clientId = form.get("client_id");
768
+ if (!token || !clientId)
769
+ return oauthError("invalid_request", "refresh_token and client_id required");
770
+ const data = await config.refreshTokens.take(token);
771
+ if (!data)
772
+ return oauthError("invalid_grant", "Unknown or used refresh token");
773
+ if (data.clientId !== clientId)
774
+ return oauthError("invalid_grant", "client_id mismatch");
775
+ const accessToken = await ctx.issueAccessToken(data.userId, data.resource, data.clientId, data.scope);
776
+ const newRefresh = randomUUID();
777
+ await config.refreshTokens.save(newRefresh, data);
778
+ return json({
779
+ access_token: accessToken,
780
+ token_type: "Bearer",
781
+ expires_in: ctx.ttl,
782
+ ...data.scope && { scope: data.scope },
783
+ refresh_token: newRefresh
784
+ });
785
+ }
786
+ return oauthError("unsupported_grant_type", `Unsupported grant_type: ${grantType ?? "none"}`);
787
+ }
788
+ };
789
+ }
790
+
791
+ // src/server/oauth/provider.ts
792
+ function mountOAuthProvider(config) {
793
+ const base = config.basePath ?? "/oauth";
794
+ const ttl = config.accessTokenTtlSec ?? 3600;
795
+ const registerPath = `${base}/register`;
796
+ const authorizePath = `${base}/authorize`;
797
+ const tokenPath = `${base}/token`;
798
+ const clientRegistration = config.clientRegistration ?? {};
799
+ const dcrRegistry = clientRegistration.dcr || undefined;
800
+ const dcrEnabled = dcrRegistry !== undefined;
801
+ const cimdConfig = clientRegistration.cimd === false ? undefined : clientRegistration.cimd ?? {};
802
+ const cimdEnabled = cimdConfig !== undefined;
803
+ const resolveCimd = cimdEnabled ? createCimdResolver({
804
+ cache: cimdConfig.cache,
805
+ fetcher: cimdConfig.fetcher ?? createSecureClientMetadataFetcher(),
806
+ onCacheEvent: cimdConfig.onCacheEvent
807
+ }) : undefined;
808
+ const resolveClient = async (clientId) => {
809
+ const preRegistered = await clientRegistration.preRegistered?.get(clientId);
810
+ if (preRegistered)
811
+ return preRegistered.clientId === clientId ? preRegistered : null;
812
+ const clientUrl = absoluteClientUrl(clientId);
813
+ if (clientUrl) {
814
+ if (!resolveCimd || clientUrl.protocol !== "https:")
815
+ return null;
816
+ try {
817
+ return await resolveCimd(clientId);
818
+ } catch {
819
+ return null;
820
+ }
821
+ }
822
+ const dcrClient = await dcrRegistry?.get(clientId);
823
+ return dcrClient?.clientId === clientId ? dcrClient : null;
824
+ };
825
+ const redirectToClient = (uri, params) => redirectWith(uri, { ...params, iss: config.issuer });
826
+ const issueAccessToken = (userId, audience, clientId, scope) => signJwt({ scope, client_id: clientId }, config.signingSecret, {
827
+ issuer: config.issuer,
828
+ audience,
829
+ subject: userId,
830
+ expiresInSec: ttl
831
+ });
832
+ const ctx = {
833
+ config,
834
+ ttl,
835
+ paths: { register: registerPath, authorize: authorizePath, token: tokenPath },
836
+ dcrRegistry,
837
+ cimdEnabled,
838
+ resolveClient,
839
+ redirectToClient,
840
+ issueAccessToken
841
+ };
842
+ return dcrEnabled ? [metadataRoute(ctx), registerRoute(ctx), authorizeRoute(ctx), tokenRoute(ctx)] : [metadataRoute(ctx), authorizeRoute(ctx), tokenRoute(ctx)];
843
+ }
844
+ // src/tools/lifecycle.ts
845
+ function composeToolLifecycle(...hooks) {
846
+ return {
847
+ beforeHandle: async (ctx, endpoint) => {
848
+ for (const hook of hooks)
849
+ await hook?.beforeHandle?.(ctx, endpoint);
850
+ },
851
+ afterHandle: async (ctx, result, endpoint) => {
852
+ let current = result;
853
+ for (const hook of hooks) {
854
+ const transformed = await hook?.afterHandle?.(ctx, current, endpoint);
855
+ if (transformed !== undefined)
856
+ current = transformed;
857
+ }
858
+ return current;
859
+ }
860
+ };
861
+ }
862
+ // src/tools/list-names.ts
863
+ function listToolNames(surface) {
864
+ const entries = new Map;
865
+ for (const transport of TOOL_TRANSPORTS) {
866
+ for (const entry of collectToolSurface({
867
+ surface,
868
+ transport,
869
+ assertNames: false,
870
+ assertUniqueNames: false
871
+ })) {
872
+ const id = `${entry.kind}\x00${entry.service}\x00${entry.action}`;
873
+ const existing = entries.get(id);
874
+ if (existing) {
875
+ existing.transports.push(transport);
876
+ } else {
877
+ entries.set(id, {
878
+ kind: entry.kind,
879
+ name: entry.mountable.name,
880
+ service: entry.service,
881
+ method: entry.action,
882
+ transports: [transport]
883
+ });
884
+ }
885
+ }
886
+ }
887
+ return [...entries.values()].sort((a, b) => a.name.localeCompare(b.name) || a.service.localeCompare(b.service));
888
+ }
889
+ function listContractToolNames(contracts) {
890
+ return listToolNames({ services: contracts.map(contractOnlyService) });
891
+ }
892
+ // src/tools/mcp/app.ts
893
+ import { readFileSync } from "node:fs";
894
+ import { fileURLToPath } from "node:url";
895
+ var RESOURCE_MIME_TYPE = "text/html;profile=mcp-app";
896
+ var EXT_APPS_BUNDLE_PLACEHOLDER = "/*__EXT_APPS_BUNDLE__*/";
897
+ function inlineMcpAppBundle(html) {
898
+ if (!html.includes(EXT_APPS_BUNDLE_PLACEHOLDER))
899
+ return html;
900
+ let bundlePath;
901
+ try {
902
+ bundlePath = fileURLToPath(import.meta.resolve("@modelcontextprotocol/ext-apps/app-with-deps"));
903
+ } catch {
904
+ throw new Error("[stitchkit] inlineMcpAppBundle: '@modelcontextprotocol/ext-apps' is not installed. " + "Add it as a dependency to serve MCP App widgets.");
905
+ }
906
+ const bundle = readFileSync(bundlePath, "utf8").replace(/export\{([^}]+)\};?\s*$/, (_match, body) => `globalThis.ExtApps={${body.split(",").map((pair) => {
907
+ const [local, exported] = pair.split(" as ").map((s) => s.trim());
908
+ return `${exported ?? local}:${local}`;
909
+ }).join(",")}};`);
910
+ return html.replace(EXT_APPS_BUNDLE_PLACEHOLDER, () => bundle);
911
+ }
912
+ // src/tools/mcp/catalog.ts
913
+ import { createHash } from "node:crypto";
914
+ var MCP_CATALOG_META_KEY = "stitchkit/catalog";
915
+ var stampCache = new WeakMap;
916
+ function toolFingerprint(descriptor) {
917
+ const { mountable } = descriptor;
918
+ return {
919
+ name: mountable.name,
920
+ description: mountable.method.desc,
921
+ input: descriptor.inputSchema,
922
+ output: descriptor.outputSchema ? toJsonSchema(descriptor.outputSchema, "output", "any") : null,
923
+ annotations: mountable.method.annotations ?? null
924
+ };
925
+ }
926
+ function mcpCatalogStamp(surface) {
927
+ const cached = stampCache.get(surface);
928
+ if (cached)
929
+ return cached;
930
+ const descriptors = [
931
+ ...surface.contractTools,
932
+ ...surface.runtimeTools.map((entry) => entry.descriptor)
933
+ ].sort((left, right) => compareCodeUnits(left.mountable.name, right.mountable.name));
934
+ const bytes = serializeCanonicalJson(descriptors.map(toolFingerprint));
935
+ const stamp = {
936
+ digest: createHash("sha256").update(bytes).digest("hex").slice(0, 16),
937
+ tools: descriptors.length
938
+ };
939
+ stampCache.set(surface, stamp);
940
+ return stamp;
941
+ }
942
+ function mcpCatalogMeta(stamp) {
943
+ return { [MCP_CATALOG_META_KEY]: { ...stamp } };
944
+ }
945
+ function readMcpCatalogStamp(meta) {
946
+ if (!isRecord(meta))
947
+ return null;
948
+ const value = meta[MCP_CATALOG_META_KEY];
949
+ if (!isRecord(value))
950
+ return null;
951
+ const { digest, tools } = value;
952
+ if (typeof digest !== "string" || digest.length === 0)
953
+ return null;
954
+ if (typeof tools !== "number" || !Number.isInteger(tools) || tools < 0)
955
+ return null;
956
+ return { digest, tools };
957
+ }
958
+ function stampToolRegistration(config, stamp) {
959
+ if (!stamp)
960
+ return config;
961
+ return { ...config, _meta: { ...config._meta, ...mcpCatalogMeta(stamp) } };
962
+ }
963
+ function stampToolResult(result, stamp) {
964
+ if (!stamp)
965
+ return result;
966
+ return { ...result, _meta: { ...result._meta, ...mcpCatalogMeta(stamp) } };
967
+ }
968
+ // src/tools/mcp/handler.ts
969
+ import {
970
+ createMcpHandler as createSdkMcpHandler,
971
+ hostHeaderValidationResponse,
972
+ localhostAllowedHostnames,
973
+ localhostAllowedOrigins,
974
+ originValidationResponse
975
+ } from "@modelcontextprotocol/server";
976
+
977
+ // src/tools/mcp/mount.ts
978
+ import {
979
+ createRequestStateCodec,
980
+ McpServer
981
+ } from "@modelcontextprotocol/server";
982
+
983
+ // src/tools/mcp/prepare.ts
984
+ function textBlock(text) {
985
+ return [{ type: "text", text }];
986
+ }
987
+ function formatMcpResult(result, mode, toolName, errorHint) {
988
+ if (result.ok) {
989
+ if (mode === "none")
990
+ return { content: [] };
991
+ let serialized;
992
+ try {
993
+ serialized = JSON.stringify(result.data, null, 2);
994
+ } catch {
995
+ serialized = undefined;
996
+ }
997
+ if (serialized === undefined) {
998
+ const safe = redact(result.data, { sensitiveKeys: /(?!)/ });
999
+ return { content: textBlock(JSON.stringify(safe, null, 2)), structuredContent: safe };
1000
+ }
1001
+ return { content: textBlock(serialized), structuredContent: result.data };
1002
+ }
1003
+ return {
1004
+ content: textBlock(JSON.stringify(formatToolError(result, toolName, errorHint), null, 2)),
1005
+ isError: true
1006
+ };
1007
+ }
1008
+ function prepareMcpSurface(services, config = {}) {
1009
+ const serviceList = Array.isArray(services) ? services : [services];
1010
+ const tools = serviceList.flatMap((service) => collectTools(service, "MCP", config));
1011
+ return prepareMcpTools(tools, config);
1012
+ }
1013
+ function prepareMcpTools(tools, config = {}) {
1014
+ const prepared = prepareProjectedMcpTools(tools.map((mountable) => {
1015
+ const outputSchema = toolSurfaceOutputSchema(mountable.method);
1016
+ return {
1017
+ tool: mountable,
1018
+ name: mountable.name,
1019
+ ...mountable.method.paramsSchema !== undefined && {
1020
+ paramsSchema: mountable.method.paramsSchema
1021
+ },
1022
+ ...mountable.method.inputSchema !== undefined && {
1023
+ inputSchema: mountable.method.inputSchema
1024
+ },
1025
+ ...mountable.method.toolView?.defaults !== undefined && {
1026
+ inputDefaults: mountable.method.toolView.defaults
1027
+ },
1028
+ ...outputSchema !== undefined && { outputSchema },
1029
+ shouldExtend: mountable.shouldExtend,
1030
+ ...mountable.method.mcp !== undefined && { mcp: mountable.method.mcp }
1031
+ };
1032
+ }), config).map((entry) => {
1033
+ Object.freeze(entry.tool);
1034
+ return Object.freeze({
1035
+ mountable: entry.tool,
1036
+ inputSchema: entry.inputSchema,
1037
+ ...entry.outputSchema !== undefined && { outputSchema: entry.outputSchema },
1038
+ outputMode: entry.outputSchema === undefined ? "none" : "direct"
1039
+ });
1040
+ });
1041
+ return Object.freeze(prepared);
1042
+ }
1043
+ function prepareMcpServerSurface(surface, config = {}) {
1044
+ const contractMountables = [];
1045
+ const definitions = [];
1046
+ const runtimeMountables = [];
1047
+ for (const entry of collectToolSurface({
1048
+ surface,
1049
+ transport: "MCP",
1050
+ extend: config.extend,
1051
+ flattenUnionInput: config.flattenUnionInput
1052
+ })) {
1053
+ if (entry.kind === "contract") {
1054
+ contractMountables.push(entry.mountable);
1055
+ } else {
1056
+ definitions.push(entry.definition);
1057
+ runtimeMountables.push(entry.mountable);
1058
+ }
1059
+ }
1060
+ const contractTools = prepareMcpTools(contractMountables, config);
1061
+ const runtimeDescriptors = prepareMcpTools(runtimeMountables, {
1062
+ schemaValidation: config.schemaValidation,
1063
+ logger: config.logger,
1064
+ multiRound: config.multiRound
1065
+ });
1066
+ const descriptorsByName = new Map(runtimeDescriptors.map((descriptor) => [descriptor.mountable.name, descriptor]));
1067
+ const runtimeTools = [];
1068
+ for (const definition of definitions) {
1069
+ const descriptor = descriptorsByName.get(definition.name);
1070
+ if (descriptor)
1071
+ runtimeTools.push(Object.freeze({ definition, descriptor }));
1072
+ }
1073
+ return Object.freeze({ contractTools, runtimeTools: Object.freeze(runtimeTools) });
1074
+ }
1075
+
1076
+ // src/tools/mcp/register.ts
1077
+ import {
1078
+ isCallToolResult
1079
+ } from "@modelcontextprotocol/server";
1080
+ import { z as z3 } from "zod";
1081
+
1082
+ // src/tools/mcp/round.ts
1083
+ import {
1084
+ acceptedContent,
1085
+ inputRequired,
1086
+ inputResponse
1087
+ } from "@modelcontextprotocol/server";
1088
+ import { z as z2 } from "zod";
1089
+
1090
+ // src/tools/mcp/round-context.ts
1091
+ import {
1092
+ CLIENT_INFO_META_KEY,
1093
+ PROTOCOL_VERSION_META_KEY
1094
+ } from "@modelcontextprotocol/server";
1095
+
1096
+ // src/tools/mcp/progress.ts
1097
+ function mcpProgressToken(context) {
1098
+ const token = context.mcpReq._meta?.progressToken;
1099
+ return typeof token === "string" || typeof token === "number" ? token : undefined;
1100
+ }
1101
+ function createMcpProgressReporter(context) {
1102
+ const token = mcpProgressToken(context);
1103
+ if (token === undefined)
1104
+ return async () => {
1105
+ return;
1106
+ };
1107
+ let sent = 0;
1108
+ let highWater = 0;
1109
+ return async (update) => {
1110
+ sent += 1;
1111
+ const value = update.progress ?? Math.max(sent, highWater + 1);
1112
+ highWater = Math.max(highWater, value);
1113
+ try {
1114
+ await context.mcpReq.notify({
1115
+ method: "notifications/progress",
1116
+ params: {
1117
+ progressToken: token,
1118
+ progress: value,
1119
+ ...update.total !== undefined && { total: update.total },
1120
+ ...update.message !== undefined && { message: update.message }
1121
+ }
1122
+ });
1123
+ } catch {}
1124
+ };
1125
+ }
1126
+
1127
+ // src/tools/mcp/round-context.ts
1128
+ function transportContext(context, toolName, outcome, round) {
1129
+ const protocolVersionValue = isRecord(context.mcpReq.envelope) ? Reflect.get(context.mcpReq.envelope, PROTOCOL_VERSION_META_KEY) : undefined;
1130
+ const protocolVersion = typeof protocolVersionValue === "string" ? protocolVersionValue : undefined;
1131
+ const clientInfoValue = isRecord(context.mcpReq.envelope) ? Reflect.get(context.mcpReq.envelope, CLIENT_INFO_META_KEY) : undefined;
1132
+ const clientInfo = isRecord(clientInfoValue) && typeof clientInfoValue.name === "string" && typeof clientInfoValue.version === "string" ? { name: clientInfoValue.name, version: clientInfoValue.version } : undefined;
1133
+ const token = mcpProgressToken(context);
1134
+ return {
1135
+ signal: context.mcpReq.signal,
1136
+ mcp: {
1137
+ era: context.mcpReq.envelope ? "modern" : "legacy",
1138
+ method: context.mcpReq.method,
1139
+ toolName,
1140
+ ...protocolVersion !== undefined && { protocolVersion },
1141
+ ...clientInfo !== undefined && { clientInfo },
1142
+ ...outcome !== undefined && { outcome },
1143
+ ...round !== undefined && { round },
1144
+ ...token !== undefined && { progressToken: token }
1145
+ },
1146
+ reportProgress: createMcpProgressReporter(context)
1147
+ };
1148
+ }
1149
+ function operationIdentity(tool) {
1150
+ return {
1151
+ toolName: tool.name,
1152
+ serviceName: tool.method.serviceName,
1153
+ action: tool.method.key,
1154
+ method: tool.method.method,
1155
+ ...tool.method.scope !== undefined && { scope: tool.method.scope }
1156
+ };
1157
+ }
1158
+ function sameIdentity(left, right) {
1159
+ return left.toolName === right.toolName && left.serviceName === right.serviceName && left.action === right.action && left.method === right.method && left.scope === right.scope;
1160
+ }
1161
+ async function runRoundSuccess(tool, rawArgs, runTool, context) {
1162
+ return runTool({
1163
+ ...tool,
1164
+ method: {
1165
+ ...tool.method,
1166
+ outputSchema: undefined,
1167
+ handler: () => {
1168
+ return;
1169
+ }
1170
+ }
1171
+ }, rawArgs, context);
1172
+ }
1173
+ async function runRoundFailure(tool, rawArgs, runTool, context, code, message) {
1174
+ return runTool({
1175
+ ...tool,
1176
+ method: {
1177
+ ...tool.method,
1178
+ outputSchema: undefined,
1179
+ handler: () => {
1180
+ throw new AppError(code, message, 400);
1181
+ }
1182
+ }
1183
+ }, rawArgs, context);
1184
+ }
1185
+ async function failedResolution(options) {
1186
+ const result = await runRoundFailure(options.tool, options.rawArgs, options.runTool, options.context, options.code, options.message);
1187
+ return { kind: "response", response: options.formatFailure(result) };
1188
+ }
1189
+
1190
+ // src/tools/mcp/round.ts
1191
+ function roundPlanDigest(requests) {
1192
+ return argumentsDigest({
1193
+ plan: requests.map((request) => ({
1194
+ key: request.key,
1195
+ message: request.message,
1196
+ schema: z2.toJSONSchema(request.schema, { io: "input", unrepresentable: "any" })
1197
+ }))
1198
+ });
1199
+ }
1200
+ async function resolveRequests(options, policy) {
1201
+ const declared = staticInputRounds(policy);
1202
+ if (declared)
1203
+ return { requests: declared, guarded: false };
1204
+ const parsed = parseToolCallArguments(options.tool.method, options.rawArgs, {
1205
+ coerceJson: options.coerceJsonArgs ?? true,
1206
+ toolSurface: true
1207
+ });
1208
+ if (!parsed.ok) {
1209
+ return { requests: [], guarded: false };
1210
+ }
1211
+ const resolver = policy.inputRequired;
1212
+ const resolved = await resolver({ params: parsed.params, input: parsed.input });
1213
+ validateResolvedInputRounds(options.tool, resolved, options.runtime?.maxRounds ?? 1);
1214
+ return { requests: resolved, guarded: false };
1215
+ }
1216
+ async function askRound(runtime, context, request, state) {
1217
+ const requestState = await runtime.codec.mint(state, context);
1218
+ return {
1219
+ kind: "response",
1220
+ response: inputRequired({
1221
+ inputRequests: {
1222
+ [request.key]: inputRequired.elicit({
1223
+ message: request.message,
1224
+ requestedSchema: request.schema
1225
+ })
1226
+ },
1227
+ requestState
1228
+ })
1229
+ };
1230
+ }
1231
+ function readRoundAnswer(context, request) {
1232
+ const view = inputResponse(context.mcpReq.inputResponses, request.key);
1233
+ if (view.kind !== "elicit") {
1234
+ return {
1235
+ refusal: {
1236
+ outcome: "invalid",
1237
+ code: "INVALID_INPUT_RESPONSE",
1238
+ message: "Expected an elicitation response for the current round"
1239
+ }
1240
+ };
1241
+ }
1242
+ if (view.action !== "accept") {
1243
+ const declined = view.action === "decline";
1244
+ return {
1245
+ refusal: {
1246
+ outcome: declined ? "declined" : "cancelled",
1247
+ code: declined ? "INPUT_DECLINED" : "INPUT_CANCELLED",
1248
+ message: declined ? "Required input was declined" : "Required input was cancelled"
1249
+ }
1250
+ };
1251
+ }
1252
+ const content = acceptedContent(context.mcpReq.inputResponses, request.key, request.schema);
1253
+ if (!content) {
1254
+ return {
1255
+ refusal: {
1256
+ outcome: "invalid",
1257
+ code: "INVALID_INPUT_RESPONSE",
1258
+ message: "Accepted input failed its declared schema"
1259
+ }
1260
+ };
1261
+ }
1262
+ return { content };
1263
+ }
1264
+ async function resolveMcpRound(options) {
1265
+ const { policy } = options;
1266
+ if (!policy) {
1267
+ return {
1268
+ kind: "continue",
1269
+ context: transportContext(options.context, options.tool.name)
1270
+ };
1271
+ }
1272
+ if (!options.runtime) {
1273
+ throw new Error(`[stitchkit] MCP tool "${options.tool.name}" declares inputRequired but no multiRound.state key is configured`);
1274
+ }
1275
+ validateMcpRoundPolicy(options.tool, policy, {
1276
+ stateConfigured: true,
1277
+ maxRounds: options.runtime.maxRounds
1278
+ });
1279
+ const state = options.context.mcpReq.requestState();
1280
+ const digest = argumentsDigest(options.rawArgs);
1281
+ if (state) {
1282
+ const mismatched = !sameIdentity(state.identity, operationIdentity(options.tool)) || state.argumentsDigest !== digest || !Number.isInteger(state.round) || state.round < 0 || state.round >= options.runtime.maxRounds || !isRecord(state.accepted);
1283
+ if (mismatched) {
1284
+ return failedResolution({
1285
+ ...options,
1286
+ context: transportContext(options.context, options.tool.name, "invalid", Number.isInteger(state.round) ? state.round : 0),
1287
+ code: "INVALID_REQUEST_STATE",
1288
+ message: "Continuation state does not match this operation, arguments or round"
1289
+ });
1290
+ }
1291
+ }
1292
+ const dynamic = staticInputRounds(policy) === undefined;
1293
+ if (dynamic) {
1294
+ const guarded = await runRoundSuccess(options.tool, options.rawArgs, options.runTool, transportContext(options.context, options.tool.name, "input_required", state?.round ?? 0));
1295
+ if (!guarded.ok)
1296
+ return { kind: "response", response: options.formatFailure(guarded) };
1297
+ }
1298
+ const resolution = await resolveRequests(options, policy);
1299
+ if ("failure" in resolution)
1300
+ return resolution.failure;
1301
+ const requests = resolution.requests;
1302
+ const alreadyGuarded = dynamic;
1303
+ const planDigest = roundPlanDigest(requests);
1304
+ if (requests.length === 0 && !state) {
1305
+ return {
1306
+ kind: "continue",
1307
+ context: transportContext(options.context, options.tool.name)
1308
+ };
1309
+ }
1310
+ if (!state) {
1311
+ if (isRecord(options.context.mcpReq.inputResponses)) {
1312
+ return failedResolution({
1313
+ ...options,
1314
+ context: transportContext(options.context, options.tool.name, "invalid", 0),
1315
+ code: "INVALID_REQUEST_STATE",
1316
+ message: "Input responses require a valid continuation state"
1317
+ });
1318
+ }
1319
+ if (!alreadyGuarded) {
1320
+ const guarded = await runRoundSuccess(options.tool, options.rawArgs, options.runTool, transportContext(options.context, options.tool.name, "input_required", 0));
1321
+ if (!guarded.ok) {
1322
+ return { kind: "response", response: options.formatFailure(guarded) };
1323
+ }
1324
+ }
1325
+ const request2 = requests[0];
1326
+ if (!request2)
1327
+ throw new Error("[stitchkit] validated MRTR policy has no first round");
1328
+ return askRound(options.runtime, options.context, request2, {
1329
+ identity: operationIdentity(options.tool),
1330
+ argumentsDigest: digest,
1331
+ round: 0,
1332
+ accepted: {},
1333
+ planDigest
1334
+ });
1335
+ }
1336
+ if (state.planDigest !== planDigest || state.round >= requests.length) {
1337
+ return failedResolution({
1338
+ ...options,
1339
+ context: transportContext(options.context, options.tool.name, "invalid", state.round),
1340
+ code: "INVALID_REQUEST_STATE",
1341
+ message: state.round >= requests.length ? "Continuation state does not match this operation, arguments or round" : "The questions for this call changed between rounds"
1342
+ });
1343
+ }
1344
+ const request = requests[state.round];
1345
+ if (!request)
1346
+ throw new Error("[stitchkit] validated MRTR state points outside its policy");
1347
+ const answer = readRoundAnswer(options.context, request);
1348
+ if ("refusal" in answer) {
1349
+ return failedResolution({
1350
+ ...options,
1351
+ context: transportContext(options.context, options.tool.name, answer.refusal.outcome, state.round),
1352
+ code: answer.refusal.code,
1353
+ message: answer.refusal.message
1354
+ });
1355
+ }
1356
+ const { content } = answer;
1357
+ const accepted = { ...state.accepted, [request.key]: content };
1358
+ const nextRound = state.round + 1;
1359
+ const nextRequest = requests[nextRound];
1360
+ if (nextRequest) {
1361
+ if (!alreadyGuarded) {
1362
+ const guarded = await runRoundSuccess(options.tool, options.rawArgs, options.runTool, transportContext(options.context, options.tool.name, "input_required", nextRound));
1363
+ if (!guarded.ok) {
1364
+ return { kind: "response", response: options.formatFailure(guarded) };
1365
+ }
1366
+ }
1367
+ return askRound(options.runtime, options.context, nextRequest, {
1368
+ identity: state.identity,
1369
+ argumentsDigest: state.argumentsDigest,
1370
+ round: nextRound,
1371
+ accepted,
1372
+ planDigest
1373
+ });
1374
+ }
1375
+ return {
1376
+ kind: "continue",
1377
+ context: {
1378
+ ...transportContext(options.context, options.tool.name, "complete", state.round),
1379
+ mcpInput: accepted
1380
+ }
1381
+ };
1382
+ }
1383
+
1384
+ // src/tools/mcp/trace.ts
1385
+ import {
1386
+ BAGGAGE_META_KEY,
1387
+ TRACEPARENT_META_KEY,
1388
+ TRACESTATE_META_KEY
1389
+ } from "@modelcontextprotocol/server";
1390
+ function runInMcpRequestContext(context, toolName, body) {
1391
+ const ambient = getRequestContext();
1392
+ const metadata = context.mcpReq._meta;
1393
+ const propagation = metadata ? {
1394
+ traceparent: metadata[TRACEPARENT_META_KEY],
1395
+ tracestate: metadata[TRACESTATE_META_KEY],
1396
+ baggage: metadata[BAGGAGE_META_KEY]
1397
+ } : undefined;
1398
+ const request = {
1399
+ ...ambient ?? {
1400
+ source: "mcp",
1401
+ method: "MCP",
1402
+ path: `/mcp/${toolName}`,
1403
+ startedAt: process.hrtime.bigint()
1404
+ },
1405
+ trace: resolvePropagationContext(propagation, ambient?.trace),
1406
+ source: "mcp",
1407
+ method: "MCP",
1408
+ path: `/mcp/${toolName}`,
1409
+ startedAt: process.hrtime.bigint(),
1410
+ dimensions: ambient?.dimensions ? { ...ambient.dimensions } : undefined,
1411
+ error: undefined
1412
+ };
1413
+ return runWithRequestContext(request, body);
1414
+ }
1415
+
1416
+ // src/tools/mcp/register.ts
1417
+ function registerMcpTool(server, presentation, descriptor, config) {
1418
+ const { mountable } = descriptor;
1419
+ const toolConfig = {
1420
+ description: presentation.description,
1421
+ inputSchema: z3.looseObject({}).meta(presentationMetadata(descriptor.inputSchema))
1422
+ };
1423
+ if (descriptor.outputSchema)
1424
+ toolConfig.outputSchema = descriptor.outputSchema;
1425
+ if (presentation.annotations)
1426
+ toolConfig.annotations = presentation.annotations;
1427
+ if (presentation.ui) {
1428
+ toolConfig._meta = {
1429
+ ui: presentation.ui,
1430
+ "ui/resourceUri": presentation.ui.resourceUri
1431
+ };
1432
+ }
1433
+ const { name } = presentation;
1434
+ const format = config.formatResult;
1435
+ server.registerTool(name, stampToolRegistration(toolConfig, config.catalog), async (rawArgs, mcpContext) => stampToolResult(await runInMcpRequestContext(mcpContext, name, async () => {
1436
+ const args = isRecord(rawArgs) ? rawArgs : {};
1437
+ try {
1438
+ const round = await resolveMcpRound({
1439
+ tool: mountable,
1440
+ rawArgs: args,
1441
+ context: mcpContext,
1442
+ policy: mountable.method.mcp,
1443
+ runtime: config.multiRoundRuntime,
1444
+ runTool: config.runTool,
1445
+ formatFailure: (result2) => format(result2, "none", name)
1446
+ });
1447
+ if (round.kind === "response")
1448
+ return round.response;
1449
+ const { present } = presentation;
1450
+ if (!present) {
1451
+ const result2 = await config.runTool(mountable, args, round.context);
1452
+ return format(result2, descriptor.outputMode, name);
1453
+ }
1454
+ const result = await config.runTool(mountable, args, round.context, {
1455
+ finalizeOutput: async (data) => {
1456
+ const presented = await present(data);
1457
+ if (!isRecord(presented)) {
1458
+ throw new AppError("INTERNAL_SERVER_ERROR", "Runtime MCP presenter did not return a result", 500);
1459
+ }
1460
+ if ("structuredContent" in presented || "isError" in presented) {
1461
+ throw new AppError("INTERNAL_SERVER_ERROR", "Runtime MCP presenter cannot set framework-owned structuredContent or isError", 500);
1462
+ }
1463
+ const structured = format({ ok: true, data }, descriptor.outputMode, name).structuredContent;
1464
+ const response = structured === undefined ? presented : { ...presented, structuredContent: structured };
1465
+ if (!isCallToolResult(response)) {
1466
+ throw new AppError("INTERNAL_SERVER_ERROR", "Runtime MCP presenter returned an invalid CallToolResult", 500);
1467
+ }
1468
+ return response;
1469
+ }
1470
+ });
1471
+ if (!result.ok)
1472
+ return format(result, "none", name);
1473
+ if (!isCallToolResult(result.data)) {
1474
+ throw new Error("[stitchkit] Runtime MCP presenter invariant failed");
1475
+ }
1476
+ return result.data;
1477
+ } catch (err) {
1478
+ return format(toolResultFromError(err), "none", name);
1479
+ }
1480
+ }), config.catalog));
1481
+ }
1482
+
1483
+ // src/tools/mcp/runtime-tools.ts
1484
+ function mountPreparedRuntimeMcp(server, tools, config) {
1485
+ const runTool = createToolRunner({
1486
+ source: "mcp",
1487
+ toolSurface: true,
1488
+ context: config.context,
1489
+ hooks: config.hooks,
1490
+ lifecycle: config.lifecycle,
1491
+ coerceJsonArgs: config.coerceJsonArgs,
1492
+ onOutputStrip: config.onOutputStrip
1493
+ });
1494
+ for (const { definition, descriptor } of tools) {
1495
+ const present = definition.present?.mcp;
1496
+ registerMcpTool(server, {
1497
+ name: definition.name,
1498
+ description: definition.description,
1499
+ annotations: definition.annotations,
1500
+ ui: definition.ui,
1501
+ ...present && { present: (data) => present(data) }
1502
+ }, descriptor, {
1503
+ runTool,
1504
+ formatResult: config.formatResult,
1505
+ catalog: config.catalog,
1506
+ multiRoundRuntime: config.multiRoundRuntime
1507
+ });
1508
+ }
1509
+ }
1510
+
1511
+ // src/tools/mcp/mount.ts
1512
+ function validateMcpSchemas(config) {
1513
+ prepareMcpSurface(config.services, {
1514
+ extend: config.extend,
1515
+ flattenUnionInput: config.flattenUnionInput,
1516
+ schemaValidation: config,
1517
+ logger: config.logger
1518
+ });
1519
+ }
1520
+ function mountMcp(mcpServer, services, config = {}) {
1521
+ const prepared = prepareMcpSurface(services, {
1522
+ extend: config.extend,
1523
+ flattenUnionInput: config.flattenUnionInput,
1524
+ schemaValidation: config.schemaValidation,
1525
+ logger: config.logger
1526
+ });
1527
+ mountPreparedMcp(mcpServer, prepared, {
1528
+ ...config,
1529
+ catalog: mcpCatalogStamp({ contractTools: prepared, runtimeTools: [] })
1530
+ });
1531
+ }
1532
+ function mountPreparedMcp(mcpServer, prepared, config = {}) {
1533
+ const runTool = createToolRunner({
1534
+ source: "mcp",
1535
+ toolSurface: true,
1536
+ extend: config.extend,
1537
+ context: config.context,
1538
+ hooks: config.hooks,
1539
+ lifecycle: config.lifecycle,
1540
+ coerceJsonArgs: config.coerceJsonArgs,
1541
+ onOutputStrip: config.onOutputStrip
1542
+ });
1543
+ for (const descriptor of prepared) {
1544
+ const { method, name } = descriptor.mountable;
1545
+ registerMcpTool(mcpServer, {
1546
+ name,
1547
+ description: method.desc,
1548
+ annotations: method.annotations,
1549
+ ui: method.ui
1550
+ }, descriptor, {
1551
+ runTool,
1552
+ formatResult: (result, mode, toolName) => formatMcpResult(result, mode, toolName, config.errorHint),
1553
+ catalog: config.catalog,
1554
+ multiRoundRuntime: config.multiRoundRuntime
1555
+ });
1556
+ }
1557
+ }
1558
+ function buildMcpServer(config, auth) {
1559
+ if (!isMcpServerBuildConfig(config)) {
1560
+ throw new TypeError("[stitchkit] buildMcpServer requires a valid config object");
1561
+ }
1562
+ let surface;
1563
+ if (config.surfaces) {
1564
+ const key = config.selectSurface(auth);
1565
+ if (!Object.hasOwn(config.surfaces, key)) {
1566
+ throw new Error(`[stitchkit] Unknown MCP surface "${key}"`);
1567
+ }
1568
+ const selected = config.surfaces[key];
1569
+ if (!selected)
1570
+ throw new Error(`[stitchkit] Unknown MCP surface "${key}"`);
1571
+ surface = selected;
1572
+ } else {
1573
+ const services = typeof config.services === "function" ? config.services(auth) : config.services;
1574
+ const runtimeTools = typeof config.runtimeTools === "function" ? config.runtimeTools(auth) : config.runtimeTools;
1575
+ surface = { services, runtimeTools };
1576
+ }
1577
+ const prepared = prepareMcpServerSurface(surface, {
1578
+ extend: config.extend,
1579
+ flattenUnionInput: config.flattenUnionInput,
1580
+ schemaValidation: config.schemaValidation,
1581
+ logger: config.logger,
1582
+ multiRound: {
1583
+ stateConfigured: config.multiRound !== undefined,
1584
+ maxRounds: config.multiRound?.serving?.maxRounds ?? 10
1585
+ }
1586
+ });
1587
+ return buildMcpServerFromPrepared(config, auth, prepared);
1588
+ }
1589
+ function isMcpServerBuildConfig(value) {
1590
+ return isRecord(value) && isRecord(value.serverInfo);
1591
+ }
1592
+ function buildMcpServerFromPrepared(config, auth, prepared) {
1593
+ let roundCodec;
1594
+ if (config.multiRound) {
1595
+ const principal = config.multiRound.state.principal(auth);
1596
+ roundCodec = createRequestStateCodec({
1597
+ key: config.multiRound.state.key,
1598
+ ttlSeconds: config.multiRound.state.ttlSeconds,
1599
+ bind: (mcpContext) => `${mcpContext.mcpReq.method}\x00${principal}`
1600
+ });
1601
+ }
1602
+ const dynamicSurface = !config.surfaces && (typeof config.services === "function" || typeof config.runtimeTools === "function");
1603
+ const serverOptions = {
1604
+ ...config.instructions !== undefined && { instructions: config.instructions },
1605
+ ...!dynamicSurface && config.cache?.operations !== undefined && {
1606
+ cacheHints: config.cache.operations
1607
+ },
1608
+ ...config.multiRound?.serving !== undefined && {
1609
+ inputRequired: config.multiRound.serving
1610
+ },
1611
+ ...roundCodec !== undefined && {
1612
+ requestState: { verify: roundCodec.verify }
1613
+ }
1614
+ };
1615
+ const server = new McpServer(config.serverInfo, serverOptions);
1616
+ const context = config.context?.(auth);
1617
+ const catalog = mcpCatalogStamp(prepared);
1618
+ mountPreparedMcp(server, prepared.contractTools, {
1619
+ catalog,
1620
+ context,
1621
+ hooks: config.hooks,
1622
+ lifecycle: config.lifecycle,
1623
+ extend: config.extend,
1624
+ schemaValidation: config.schemaValidation,
1625
+ logger: config.logger,
1626
+ coerceJsonArgs: config.coerceJsonArgs,
1627
+ flattenUnionInput: config.flattenUnionInput,
1628
+ errorHint: config.errorHint,
1629
+ onOutputStrip: config.onOutputStrip,
1630
+ ...roundCodec !== undefined && {
1631
+ multiRoundRuntime: {
1632
+ codec: roundCodec,
1633
+ maxRounds: config.multiRound?.serving?.maxRounds ?? 10
1634
+ }
1635
+ }
1636
+ });
1637
+ mountPreparedRuntimeMcp(server, prepared.runtimeTools, {
1638
+ catalog,
1639
+ context,
1640
+ hooks: config.hooks,
1641
+ lifecycle: config.lifecycle,
1642
+ coerceJsonArgs: config.coerceJsonArgs,
1643
+ onOutputStrip: config.onOutputStrip,
1644
+ formatResult: (result, mode, toolName) => formatMcpResult(result, mode, toolName, config.errorHint),
1645
+ ...roundCodec !== undefined && {
1646
+ multiRoundRuntime: {
1647
+ codec: roundCodec,
1648
+ maxRounds: config.multiRound?.serving?.maxRounds ?? 10
1649
+ }
1650
+ }
1651
+ });
1652
+ config.rawTools?.(server, auth);
1653
+ for (const resource of config.resources ?? []) {
1654
+ mountMcpResource(server, resource);
1655
+ }
1656
+ return server;
1657
+ }
1658
+ function mountMcpResource(server, resource) {
1659
+ server.registerResource(resource.name, resource.uri, {
1660
+ mimeType: resource.mimeType ?? RESOURCE_MIME_TYPE,
1661
+ ...resource.cacheHint !== undefined && { cacheHint: resource.cacheHint }
1662
+ }, async () => ({
1663
+ contents: [
1664
+ {
1665
+ uri: resource.uri,
1666
+ mimeType: resource.mimeType ?? RESOURCE_MIME_TYPE,
1667
+ text: await resource.read(),
1668
+ ...resource.ui && { _meta: { ui: resource.ui } }
1669
+ }
1670
+ ]
1671
+ }));
1672
+ }
1673
+
1674
+ // src/tools/mcp/handler.ts
1675
+ function jsonRpcError(code, message, status, headers) {
1676
+ return Response.json({ jsonrpc: "2.0", error: { code, message }, id: null }, { status, headers });
1677
+ }
1678
+ function hostValidationResponse(request, allowedHosts) {
1679
+ if (request.headers.has("host")) {
1680
+ return hostHeaderValidationResponse(request, [...allowedHosts]);
1681
+ }
1682
+ const hostname = new URL(request.url).hostname;
1683
+ if (allowedHosts.includes(hostname))
1684
+ return;
1685
+ return jsonRpcError(-32000, "Invalid Host header", 403);
1686
+ }
1687
+ function prepareStaticSurface(config) {
1688
+ const preparation = {
1689
+ logger: config.logger,
1690
+ extend: config.extend,
1691
+ flattenUnionInput: config.flattenUnionInput,
1692
+ schemaValidation: config.schemaValidation,
1693
+ multiRound: {
1694
+ stateConfigured: config.multiRound !== undefined,
1695
+ maxRounds: config.multiRound?.serving?.maxRounds ?? 10
1696
+ }
1697
+ };
1698
+ if (config.surfaces && config.selectSurface) {
1699
+ const preparedByKey = new Map;
1700
+ const preparedBySurface = new WeakMap;
1701
+ for (const key in config.surfaces) {
1702
+ if (!Object.hasOwn(config.surfaces, key))
1703
+ continue;
1704
+ const surface = config.surfaces[key];
1705
+ if (!surface)
1706
+ continue;
1707
+ const existing = preparedBySurface.get(surface);
1708
+ const prepared = existing ?? prepareMcpServerSurface(surface, preparation);
1709
+ if (!existing)
1710
+ preparedBySurface.set(surface, prepared);
1711
+ preparedByKey.set(key, prepared);
1712
+ }
1713
+ return (auth) => {
1714
+ const key = config.selectSurface(auth);
1715
+ const prepared = preparedByKey.get(key);
1716
+ if (!prepared)
1717
+ throw new Error(`[stitchkit] Unknown MCP surface "${key}"`);
1718
+ return buildMcpServerFromPrepared(config, auth, prepared);
1719
+ };
1720
+ }
1721
+ if (config.services && typeof config.services !== "function" && typeof config.runtimeTools !== "function") {
1722
+ const prepared = prepareMcpServerSurface({ services: config.services, runtimeTools: config.runtimeTools }, preparation);
1723
+ return (auth) => buildMcpServerFromPrepared(config, auth, prepared);
1724
+ }
1725
+ return null;
1726
+ }
1727
+ function createMcpHandler(config) {
1728
+ const buildPrepared = prepareStaticSurface(config);
1729
+ const authByCarrier = new WeakMap;
1730
+ let closed = false;
1731
+ let resolveClosed;
1732
+ const closedSignal = new Promise((resolve) => {
1733
+ resolveClosed = resolve;
1734
+ });
1735
+ const sdkHandler = createSdkMcpHandler(({ authInfo }) => {
1736
+ const resolved = authInfo ? authByCarrier.get(authInfo) : undefined;
1737
+ if (!resolved) {
1738
+ throw new Error("[stitchkit] MCP request reached the SDK without resolved auth");
1739
+ }
1740
+ const auth = resolved.value;
1741
+ return buildPrepared ? buildPrepared(auth) : buildMcpServer(config, auth);
1742
+ }, {
1743
+ legacy: config.legacy === "reject" ? "reject" : "stateless",
1744
+ maxSubscriptions: 0
1745
+ });
1746
+ const unauthorized = () => {
1747
+ const headers = config.protectedResource ? { "WWW-Authenticate": wwwAuthenticateHeader(config.protectedResource.resource) } : undefined;
1748
+ return jsonRpcError(-32001, "Authorization required", 401, headers);
1749
+ };
1750
+ const observeRejection = (request, response) => {
1751
+ if (response.status < 400 || !config.onTransportRejected)
1752
+ return response;
1753
+ Promise.resolve(config.onTransportRejected({ request, response: response.clone() })).catch(() => {
1754
+ return;
1755
+ });
1756
+ return response;
1757
+ };
1758
+ return {
1759
+ fetch: async (request) => {
1760
+ if (closed) {
1761
+ return observeRejection(request, jsonRpcError(-32000, "MCP handler is closed", 503));
1762
+ }
1763
+ const allowedHosts = config.security?.allowedHosts ?? localhostAllowedHostnames();
1764
+ const hostRejection = hostValidationResponse(request, allowedHosts);
1765
+ if (hostRejection)
1766
+ return observeRejection(request, hostRejection);
1767
+ const allowedOrigins = config.security?.allowedOrigins ?? localhostAllowedOrigins();
1768
+ const originRejection = originValidationResponse(request, [...allowedOrigins]);
1769
+ if (originRejection)
1770
+ return observeRejection(request, originRejection);
1771
+ const auth = await Promise.race([
1772
+ Promise.resolve(config.auth(request)),
1773
+ closedSignal.then(() => null)
1774
+ ]);
1775
+ if (closed) {
1776
+ return observeRejection(request, jsonRpcError(-32000, "MCP handler is closed", 503));
1777
+ }
1778
+ if (auth == null)
1779
+ return observeRejection(request, unauthorized());
1780
+ const authCarrier = {
1781
+ token: "",
1782
+ clientId: config.multiRound?.state.principal(auth) ?? "stitchkit",
1783
+ scopes: []
1784
+ };
1785
+ authByCarrier.set(authCarrier, { value: auth });
1786
+ try {
1787
+ return observeRejection(request, await sdkHandler.fetch(request, { authInfo: authCarrier }));
1788
+ } finally {
1789
+ authByCarrier.delete(authCarrier);
1790
+ }
1791
+ },
1792
+ close: async () => {
1793
+ if (closed)
1794
+ return;
1795
+ closed = true;
1796
+ resolveClosed?.();
1797
+ await sdkHandler.close();
1798
+ }
1799
+ };
1800
+ }
1801
+ function createMcpHttpRoute(config) {
1802
+ return {
1803
+ method: "ALL",
1804
+ path: config.path,
1805
+ handler: (request) => config.handler.fetch(request)
1806
+ };
1807
+ }
1808
+ // src/tools/mcp/stdio.ts
1809
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
1810
+ async function createStdioMcpServer(config) {
1811
+ const auth = await config.auth;
1812
+ return serveStdio(() => buildMcpServer(config, auth), {
1813
+ legacy: config.legacy ?? "serve",
1814
+ maxSubscriptions: 0
1815
+ });
1816
+ }
1817
+ // src/tools/mcp/stdio-signals.ts
1818
+ var bound = new WeakSet;
1819
+ function bindStdioProcessSignals(handle, options = {}) {
1820
+ if (bound.has(handle)) {
1821
+ throw new Error("[stitchkit] bindStdioProcessSignals: this stdio handle is already bound; close the first binding before creating another");
1822
+ }
1823
+ bound.add(handle);
1824
+ const signals = [...new Set(options.signals ?? DEFAULT_PROCESS_SIGNALS)];
1825
+ const source = options.signalSource ?? defaultSignalSource;
1826
+ const handlers = [];
1827
+ let started = false;
1828
+ let sameTurnAsStart = false;
1829
+ let closed = false;
1830
+ let resolveChain = () => {
1831
+ return;
1832
+ };
1833
+ let rejectChain = () => {
1834
+ return;
1835
+ };
1836
+ const promise = new Promise((resolve, reject) => {
1837
+ resolveChain = resolve;
1838
+ rejectChain = reject;
1839
+ });
1840
+ promise.catch(() => {
1841
+ return;
1842
+ });
1843
+ const removeListeners = () => {
1844
+ if (closed)
1845
+ return;
1846
+ closed = true;
1847
+ for (const [signal, handler] of handlers)
1848
+ source.off(signal, handler);
1849
+ if (!started)
1850
+ bound.delete(handle);
1851
+ };
1852
+ const close = () => {
1853
+ const hadStarted = started;
1854
+ removeListeners();
1855
+ if (!hadStarted)
1856
+ resolveChain();
1857
+ };
1858
+ const run = async (signal) => {
1859
+ try {
1860
+ await options.onClose?.(signal);
1861
+ } catch (error) {
1862
+ reportSignalError("prepare", error, options.onError);
1863
+ }
1864
+ try {
1865
+ await handle.close();
1866
+ } catch (error) {
1867
+ rejectChain(error);
1868
+ reportSignalError("close", error, options.onError);
1869
+ removeListeners();
1870
+ return;
1871
+ }
1872
+ resolveChain();
1873
+ try {
1874
+ await options.onComplete?.();
1875
+ } catch (error) {
1876
+ reportSignalError("complete", error, options.onError);
1877
+ } finally {
1878
+ removeListeners();
1879
+ }
1880
+ };
1881
+ const onSignal = (signal) => {
1882
+ if (!started) {
1883
+ started = true;
1884
+ sameTurnAsStart = true;
1885
+ queueMicrotask(() => {
1886
+ sameTurnAsStart = false;
1887
+ });
1888
+ run(signal).catch((error) => reportSignalError("close", error, options.onError));
1889
+ return;
1890
+ }
1891
+ if (sameTurnAsStart)
1892
+ return;
1893
+ removeListeners();
1894
+ guardSignalCallback(() => options.onRepeatedSignal?.(signal), "close", options.onError);
1895
+ let restored = false;
1896
+ try {
1897
+ restored = source.raiseDefault(signal);
1898
+ } catch (error) {
1899
+ reportSignalError("close", error, options.onError);
1900
+ }
1901
+ if (!restored) {
1902
+ guardSignalCallback(() => options.onEscalationBlocked?.(signal), "close", options.onError);
1903
+ }
1904
+ };
1905
+ for (const signal of signals) {
1906
+ const handler = () => onSignal(signal);
1907
+ handlers.push([signal, handler]);
1908
+ source.on(signal, handler);
1909
+ }
1910
+ return { promise, close };
1911
+ }
1912
+ // src/tools/operations/async-operation-id.ts
1913
+ import { z as z4 } from "zod";
1914
+ function adapterResult(capability, target, schema, value) {
1915
+ const parsed = schema.safeParse(value);
1916
+ if (!parsed.success) {
1917
+ throw new Error(`Async operation adapter for capability "${capability}" returned invalid ${target}`, { cause: parsed.error });
1918
+ }
1919
+ return parsed.data;
1920
+ }
1921
+ var NON_WIRE_STABLE_ZOD_TYPES = new Set([
1922
+ "catch",
1923
+ "default",
1924
+ "lazy",
1925
+ "pipe",
1926
+ "prefault",
1927
+ "readonly",
1928
+ "success",
1929
+ "transform"
1930
+ ]);
1931
+ function hasOverwriteCheck(value) {
1932
+ return isRecord(value) && isRecord(value._zod) && isRecord(value._zod.def) && value._zod.def.check === "overwrite";
1933
+ }
1934
+ function assertWireStableIdSchema(schema, boundary) {
1935
+ const visited = new Set;
1936
+ const pending = [schema];
1937
+ while (pending.length > 0) {
1938
+ const value = pending.pop();
1939
+ if (typeof value !== "object" || value === null || visited.has(value))
1940
+ continue;
1941
+ visited.add(value);
1942
+ if (value instanceof z4.ZodType) {
1943
+ const definition = value._zod.def;
1944
+ if (NON_WIRE_STABLE_ZOD_TYPES.has(definition.type) || "coerce" in definition && definition.coerce === true || "checks" in definition && Array.isArray(definition.checks) && definition.checks.some(hasOverwriteCheck)) {
1945
+ throw new Error(`${boundary} must use a wire-stable ID schema without transforms, coercion, defaults or overwrites; use binding: "adapted" with explicit ID adapters`);
1946
+ }
1947
+ pending.push(...Object.values(definition));
1948
+ continue;
1949
+ }
1950
+ if (Array.isArray(value)) {
1951
+ pending.push(...value);
1952
+ continue;
1953
+ }
1954
+ if (isRecord(value))
1955
+ pending.push(...Object.values(value));
1956
+ }
1957
+ }
1958
+
1959
+ // src/tools/operations/async-operation-binding.ts
1960
+ function bindContractAsyncOperation(config) {
1961
+ const endpoint = (key) => {
1962
+ const found = config.contract.endpoints[key];
1963
+ if (!found)
1964
+ throw new Error(`Contract async operation method "${key}" not found`);
1965
+ return found;
1966
+ };
1967
+ const start = endpoint(config.capabilities.start);
1968
+ const status = endpoint(config.capabilities.status);
1969
+ const wait = endpoint(config.capabilities.wait);
1970
+ if (!start.output || !status.output || !wait.output) {
1971
+ throw new Error("Contract async operation requires outputs for start, status and wait");
1972
+ }
1973
+ const startOutput = start.output;
1974
+ const statusOutput = status.output;
1975
+ if (wait.output !== statusOutput) {
1976
+ throw new Error('Contract async operation capability "wait" output must reuse the same schema instance as the status output');
1977
+ }
1978
+ const resolved = {
1979
+ endpoint,
1980
+ status,
1981
+ wait,
1982
+ startOutput,
1983
+ statusOutput
1984
+ };
1985
+ if (config.binding !== "adapted")
1986
+ return bindDirect(config, resolved);
1987
+ return bindAdapted(config, resolved);
1988
+ }
1989
+ var OPTIONAL_CAPABILITIES = [
1990
+ "cancel",
1991
+ "result",
1992
+ "artifacts"
1993
+ ];
1994
+ function bindDirect(config, { endpoint, status, wait, startOutput, statusOutput }) {
1995
+ assertWireStableIdSchema(startOutput, "Direct contract async operation");
1996
+ if (status.input !== startOutput || wait.input !== startOutput) {
1997
+ const capability = status.input !== startOutput ? "status" : "wait";
1998
+ throw new Error(`Contract async operation capability "${capability}" input must reuse the same schema instance as the start output`);
1999
+ }
2000
+ const inputFor = {
2001
+ status: (id) => adapterResult("status", "input", startOutput, id),
2002
+ wait: (id) => adapterResult("wait", "input", startOutput, id)
2003
+ };
2004
+ for (const capability of OPTIONAL_CAPABILITIES) {
2005
+ const key = config.capabilities[capability];
2006
+ if (!key)
2007
+ continue;
2008
+ if (endpoint(key).input !== startOutput) {
2009
+ throw new Error(`Contract async operation capability "${capability}" input must reuse the same schema instance as the start output`);
2010
+ }
2011
+ inputFor[capability] = (id) => adapterResult(capability, "input", startOutput, id);
2012
+ }
2013
+ return {
2014
+ contract: config.contract,
2015
+ handlers: config.handlers,
2016
+ capabilities: config.capabilities,
2017
+ schemas: { id: startOutput, snapshot: statusOutput },
2018
+ adapters: {
2019
+ idFromStart: (output) => adapterResult("start", "id", startOutput, output),
2020
+ inputFor
2021
+ }
2022
+ };
2023
+ }
2024
+ function bindAdapted(config, { endpoint, statusOutput }) {
2025
+ const adapters = config.adapters;
2026
+ const idSchema = config.id;
2027
+ const adaptedInput = (capability, key, builder) => {
2028
+ const input = endpoint(key).input;
2029
+ if (!input) {
2030
+ throw new Error(`Contract async operation capability "${capability}" requires an input schema`);
2031
+ }
2032
+ return (id) => adapterResult(capability, "input", input, builder(id));
2033
+ };
2034
+ const inputFor = {
2035
+ status: adaptedInput("status", config.capabilities.status, adapters.inputFor.status),
2036
+ wait: adaptedInput("wait", config.capabilities.wait, adapters.inputFor.wait)
2037
+ };
2038
+ const optionalInput = (capability, key, builder) => {
2039
+ if (!key)
2040
+ return;
2041
+ if (!builder) {
2042
+ throw new Error(`Contract async operation capability "${capability}" requires an input adapter`);
2043
+ }
2044
+ inputFor[capability] = adaptedInput(capability, key, builder);
2045
+ };
2046
+ optionalInput("cancel", config.capabilities.cancel, "cancel" in adapters.inputFor ? adapters.inputFor.cancel : undefined);
2047
+ optionalInput("result", config.capabilities.result, "result" in adapters.inputFor ? adapters.inputFor.result : undefined);
2048
+ optionalInput("artifacts", config.capabilities.artifacts, "artifacts" in adapters.inputFor ? adapters.inputFor.artifacts : undefined);
2049
+ if (!idSchema) {
2050
+ throw new Error("Contract adapted async operation requires an id schema");
2051
+ }
2052
+ return {
2053
+ contract: config.contract,
2054
+ handlers: config.handlers,
2055
+ capabilities: config.capabilities,
2056
+ schemas: { id: idSchema, snapshot: statusOutput },
2057
+ adapters: {
2058
+ idFromStart: (output) => adapterResult("start", "id", idSchema, adapters.idFromStart(output)),
2059
+ inputFor
2060
+ }
2061
+ };
2062
+ }
2063
+ // src/tools/operations/async-operation-canonical.ts
2064
+ function buildCanonicalEndpointTable(config, startOutput) {
2065
+ const description = (capability) => config.descriptions?.[capability] ?? `${config.description}: ${capability}`;
2066
+ const endpoint = (capability, method, path, input, output) => {
2067
+ const scope = config.scopes?.[capability];
2068
+ const expose = config.expose?.[capability];
2069
+ return {
2070
+ method,
2071
+ path,
2072
+ desc: description(capability),
2073
+ input,
2074
+ output,
2075
+ ...scope !== undefined && { scope },
2076
+ ...expose !== undefined && { expose }
2077
+ };
2078
+ };
2079
+ const endpoints = {
2080
+ start: endpoint("start", "POST", "/", config.startInput, startOutput),
2081
+ status: endpoint("status", "POST", "/status", config.id, config.snapshot),
2082
+ wait: endpoint("wait", "POST", "/wait", config.id, config.snapshot)
2083
+ };
2084
+ const capabilities = {
2085
+ start: "start",
2086
+ status: "status",
2087
+ wait: "wait"
2088
+ };
2089
+ const schemas = {
2090
+ startInput: config.startInput,
2091
+ startOutput,
2092
+ id: config.id,
2093
+ snapshot: config.snapshot,
2094
+ cancelResult: AsyncOperationCancelResultSchema
2095
+ };
2096
+ const inputFor = {
2097
+ status: (id) => adapterResult("status", "input", config.id, id),
2098
+ wait: (id) => adapterResult("wait", "input", config.id, id)
2099
+ };
2100
+ if (config.cancel) {
2101
+ endpoints.cancel = endpoint("cancel", "POST", "/cancel", config.id, AsyncOperationCancelResultSchema);
2102
+ capabilities.cancel = "cancel";
2103
+ schemas.cancel = AsyncOperationCancelResultSchema;
2104
+ inputFor.cancel = (id) => adapterResult("cancel", "input", config.id, id);
2105
+ }
2106
+ if (config.result) {
2107
+ endpoints.result = endpoint("result", "POST", "/result", config.id, config.result);
2108
+ capabilities.result = "result";
2109
+ schemas.result = config.result;
2110
+ inputFor.result = (id) => adapterResult("result", "input", config.id, id);
2111
+ }
2112
+ if (config.artifacts) {
2113
+ endpoints.artifacts = endpoint("artifacts", "POST", "/artifacts", config.id, config.artifacts);
2114
+ capabilities.artifacts = "artifacts";
2115
+ schemas.artifacts = config.artifacts;
2116
+ inputFor.artifacts = (id) => adapterResult("artifacts", "input", config.id, id);
2117
+ }
2118
+ return { endpoints, capabilities, schemas, inputFor };
2119
+ }
2120
+ function defineAsyncOperationContract(config) {
2121
+ assertWireStableIdSchema(config.id, "Async operation contract");
2122
+ const hasStartOutput = config.startOutput !== undefined;
2123
+ const hasIdFromStart = config.idFromStart !== undefined;
2124
+ if (hasStartOutput !== hasIdFromStart) {
2125
+ throw new Error("Async operation contract startOutput and idFromStart must be configured together");
2126
+ }
2127
+ const startOutput = config.startOutput ?? config.id;
2128
+ const { endpoints, capabilities, schemas, inputFor } = buildCanonicalEndpointTable(config, startOutput);
2129
+ const contract = config.scope ? defineContract({ prefix: config.prefix, scope: config.scope }, endpoints) : defineContract({ prefix: config.prefix }, endpoints);
2130
+ const applicationStartOutput = config.startOutput;
2131
+ const applicationIdFromStart = config.idFromStart;
2132
+ const idFromStart = applicationStartOutput && applicationIdFromStart ? (output) => adapterResult("start", "id", config.id, applicationIdFromStart(output)) : (output) => adapterResult("start", "id", config.id, output);
2133
+ return {
2134
+ contract,
2135
+ capabilities,
2136
+ schemas,
2137
+ adapters: { idFromStart, inputFor }
2138
+ };
2139
+ }
2140
+ // src/tools/native-definition.ts
2141
+ function managedNativeIdentity(identity, method) {
2142
+ return { ...identity, method };
2143
+ }
2144
+
2145
+ // src/tools/operations/define-wait-tool.ts
2146
+ function defineWaitTool(config) {
2147
+ const renderedMcp = config.render ? {
2148
+ mcp: (state) => {
2149
+ const rendered = config.render?.(state, false);
2150
+ return {
2151
+ content: [
2152
+ {
2153
+ type: "text",
2154
+ text: rendered?.text ?? JSON.stringify(state, null, 2)
2155
+ }
2156
+ ]
2157
+ };
2158
+ }
2159
+ } : undefined;
2160
+ const present = renderedMcp || config.present ? { ...renderedMcp, ...config.present } : undefined;
2161
+ return defineRuntimeTool({
2162
+ name: config.name ?? "wait",
2163
+ description: config.description,
2164
+ identity: managedNativeIdentity(config.identity, "GET"),
2165
+ input: config.input,
2166
+ output: config.state,
2167
+ transports: config.transports,
2168
+ annotations: config.annotations,
2169
+ present,
2170
+ handler: async (context) => {
2171
+ let result;
2172
+ try {
2173
+ result = await runWaitOperation({
2174
+ input: context.input,
2175
+ poll: async (input, signal) => config.state.parse(await config.poll(input, { ...context, signal })),
2176
+ done: config.done,
2177
+ backoff: config.backoff,
2178
+ timeoutSec: config.timeoutFromInput?.(context.input) ?? config.defaultTimeout,
2179
+ signal: context.signal
2180
+ });
2181
+ } catch (error) {
2182
+ if (error instanceof WaitTimeoutError) {
2183
+ throw new AppError("WAIT_TIMEOUT", "Wait timed out before the first snapshot", 408);
2184
+ }
2185
+ throw error;
2186
+ }
2187
+ const rendered = config.render?.(result.state, result.timedOut);
2188
+ if (result.timedOut) {
2189
+ throw new AppError("WAIT_TIMEOUT", rendered?.text ?? "Wait timed out before the operation completed", 408);
2190
+ }
2191
+ if (rendered?.isError) {
2192
+ throw new AppError("WAIT_FAILED", rendered.text, 409);
2193
+ }
2194
+ return result.state;
2195
+ }
2196
+ });
2197
+ }
2198
+
2199
+ // src/tools/operations/async-operation-runtime-tools.ts
2200
+ function terminal(snapshot) {
2201
+ if (typeof snapshot !== "object" || snapshot === null || !("phase" in snapshot)) {
2202
+ return false;
2203
+ }
2204
+ return snapshot.phase === "succeeded" || snapshot.phase === "failed" || snapshot.phase === "cancelled";
2205
+ }
2206
+ function succeeded(snapshot) {
2207
+ return typeof snapshot === "object" && snapshot !== null && "phase" in snapshot && snapshot.phase === "succeeded";
2208
+ }
2209
+ function createRuntimeOperationSurface(config) {
2210
+ const capabilityName = (capability) => config.names?.[capability] ?? `${config.name}_${capability}`;
2211
+ const description = (capability) => config.descriptions?.[capability] ?? `${config.description}: ${capability}`;
2212
+ return {
2213
+ config,
2214
+ identity: (capability, method) => ({
2215
+ serviceName: config.identity.serviceName,
2216
+ action: `${config.identity.action}.${capability}`,
2217
+ scope: config.scopes?.[capability] ?? config.identity.scope,
2218
+ meta: config.identity.meta,
2219
+ method
2220
+ }),
2221
+ common: (capability) => ({
2222
+ name: capabilityName(capability),
2223
+ description: description(capability),
2224
+ transports: config.transports?.[capability],
2225
+ annotations: config.annotations?.[capability] ?? (capability === "start" || capability === "cancel" ? { destructiveHint: true } : undefined)
2226
+ }),
2227
+ inspect: async (capability, context) => {
2228
+ await config.authorize(context.input, capability, context);
2229
+ const state = config.state.parse(await config.inspect(context.input, context));
2230
+ const snapshot = config.snapshot.parse(await config.classify(state, context));
2231
+ return { state, snapshot };
2232
+ }
2233
+ };
2234
+ }
2235
+ function defineObservationTools(surface) {
2236
+ const { config } = surface;
2237
+ const status = defineRuntimeTool({
2238
+ ...surface.common("status"),
2239
+ identity: surface.identity("status", "GET"),
2240
+ input: config.id,
2241
+ output: config.snapshot,
2242
+ handler: async (context) => (await surface.inspect("status", context)).snapshot
2243
+ });
2244
+ const wait = defineWaitTool({
2245
+ ...surface.common("wait"),
2246
+ identity: surface.identity("wait", "GET"),
2247
+ input: config.id,
2248
+ state: config.snapshot,
2249
+ poll: async (_id, context) => (await surface.inspect("wait", context)).snapshot,
2250
+ done: terminal,
2251
+ backoff: config.backoff,
2252
+ defaultTimeout: config.defaultTimeout,
2253
+ timeoutFromInput: config.timeoutFromId
2254
+ });
2255
+ return { status, wait };
2256
+ }
2257
+ function defineCancelTool(surface, capability) {
2258
+ return defineRuntimeTool({
2259
+ ...surface.common("cancel"),
2260
+ identity: surface.identity("cancel", "DELETE"),
2261
+ input: surface.config.id,
2262
+ output: AsyncOperationCancelResultSchema,
2263
+ handler: async (context) => {
2264
+ const inspected = await surface.inspect("cancel", context);
2265
+ return capability.handler(inspected.state, context);
2266
+ }
2267
+ });
2268
+ }
2269
+ function defineSucceededOutputTool(surface, kind, capability, unavailableMessage) {
2270
+ return defineRuntimeTool({
2271
+ ...surface.common(kind),
2272
+ identity: surface.identity(kind, "GET"),
2273
+ input: surface.config.id,
2274
+ output: capability.output,
2275
+ handler: async (context) => {
2276
+ const inspected = await surface.inspect(kind, context);
2277
+ if (!succeeded(inspected.snapshot)) {
2278
+ throw new AppError("OPERATION_NOT_SUCCEEDED", unavailableMessage, 409);
2279
+ }
2280
+ return capability.handler(inspected.state, context);
2281
+ }
2282
+ });
2283
+ }
2284
+
2285
+ // src/tools/operations/async-operation-runtime.ts
2286
+ function defineAsyncOperation(config) {
2287
+ const surface = createRuntimeOperationSurface(config);
2288
+ const start = defineRuntimeTool({
2289
+ ...surface.common("start"),
2290
+ identity: surface.identity("start", "POST"),
2291
+ input: config.startInput,
2292
+ output: config.id,
2293
+ handler: (context) => config.start(context.input, context)
2294
+ });
2295
+ const { status, wait } = defineObservationTools(surface);
2296
+ const definitions = { start, status, wait };
2297
+ const names = new Set;
2298
+ if (config.cancel) {
2299
+ definitions.cancel = defineCancelTool(surface, config.cancel);
2300
+ }
2301
+ if (config.result) {
2302
+ definitions.result = defineSucceededOutputTool(surface, "result", config.result, "Operation result is not available");
2303
+ }
2304
+ if (config.artifacts) {
2305
+ definitions.artifacts = defineSucceededOutputTool(surface, "artifacts", config.artifacts, "Operation artifacts are not available");
2306
+ }
2307
+ for (const definition of Object.values(definitions)) {
2308
+ assertUniqueToolName(definition.name, names.has(definition.name), "in-process tool name");
2309
+ names.add(definition.name);
2310
+ }
2311
+ return {
2312
+ ...definitions,
2313
+ runtimeTools: Object.values(definitions),
2314
+ schemas: {
2315
+ id: config.id,
2316
+ snapshot: config.snapshot,
2317
+ cancelResult: AsyncOperationCancelResultSchema
2318
+ }
2319
+ };
2320
+ }
2321
+ // src/tools/operations/mount-wait.ts
2322
+ import { z as z5 } from "zod";
2323
+
2324
+ // src/tools/transfer/native-result.ts
2325
+ function textResult(text, isError = false) {
2326
+ const content = [{ type: "text", text }];
2327
+ return isError ? { content, isError: true } : { content };
2328
+ }
2329
+
2330
+ // src/tools/operations/mount-wait.ts
2331
+ function mountWait(server, config) {
2332
+ const name = config.name ?? "wait";
2333
+ assertToolName(name, "<native>", "wait");
2334
+ server.registerTool(name, { description: config.description, inputSchema: z5.object(config.inputSchema) }, async (rawArgs, mcpContext) => {
2335
+ const args = isRecord(rawArgs) ? rawArgs : {};
2336
+ const report = createMcpProgressReporter(mcpContext);
2337
+ let last;
2338
+ try {
2339
+ const { state, timedOut } = await runWaitOperation({
2340
+ input: args,
2341
+ poll: async (input) => {
2342
+ last = await config.poll(input);
2343
+ return last;
2344
+ },
2345
+ done: config.done,
2346
+ backoff: config.backoff,
2347
+ timeoutSec: config.timeoutFromArgs?.(args) ?? config.defaultTimeout,
2348
+ onTick: (attempt, elapsedSec) => {
2349
+ const snapshot = isRecord(last) ? last : undefined;
2350
+ const phase = typeof snapshot?.phase === "string" ? snapshot.phase : undefined;
2351
+ const measured = typeof snapshot?.progress === "number" && Number.isFinite(snapshot.progress) ? snapshot.progress : undefined;
2352
+ report({
2353
+ progress: measured ?? attempt,
2354
+ message: phase ? `${phase} — poll ${attempt}, ${Math.round(elapsedSec)}s elapsed` : `poll ${attempt}, ${Math.round(elapsedSec)}s elapsed`
2355
+ });
2356
+ }
2357
+ });
2358
+ const rendered = config.render ? config.render(state, timedOut) : { text: JSON.stringify(state, null, 2), isError: timedOut };
2359
+ return textResult(rendered.text, rendered.isError);
2360
+ } catch (err) {
2361
+ return textResult(`Wait failed: ${err instanceof Error ? err.message : String(err)}`, true);
2362
+ }
2363
+ });
2364
+ }
2365
+ // src/tools/registry.ts
2366
+ function defineToolRegistry(input) {
2367
+ const defaults = [...input.defaults];
2368
+ const slots = new Set;
2369
+ for (const tool of defaults) {
2370
+ if (!tool.name)
2371
+ throw new Error("A default tool must carry a non-empty name");
2372
+ if (slots.has(tool.name))
2373
+ throw new Error(`Duplicate default tool name: ${tool.name}`);
2374
+ slots.add(tool.name);
2375
+ }
2376
+ const disabled = new Set;
2377
+ const replacements = new Map;
2378
+ const assertKnown = (name, verb) => {
2379
+ if (!slots.has(name)) {
2380
+ throw new Error(`Tool registry ${verb}("${name}") names no default; declared: ${[...slots].sort().join(", ") || "(none)"}`);
2381
+ }
2382
+ };
2383
+ const builder = {
2384
+ replace(name, tool) {
2385
+ assertKnown(name, "replace");
2386
+ if (disabled.has(name)) {
2387
+ throw new Error(`Tool registry cannot replace "${name}": it is disabled`);
2388
+ }
2389
+ if (replacements.has(name)) {
2390
+ throw new Error(`Tool registry already replaced "${name}"`);
2391
+ }
2392
+ if (tool.name !== name) {
2393
+ throw new Error(`A replacement for "${name}" must carry that name, not "${tool.name}"`);
2394
+ }
2395
+ replacements.set(name, tool);
2396
+ return builder;
2397
+ },
2398
+ disable(name) {
2399
+ assertKnown(name, "disable");
2400
+ disabled.add(name);
2401
+ return builder;
2402
+ },
2403
+ build() {
2404
+ const tools = [];
2405
+ const seen = new Set;
2406
+ for (const tool of defaults) {
2407
+ if (disabled.has(tool.name))
2408
+ continue;
2409
+ const effective = replacements.get(tool.name) ?? tool;
2410
+ if (seen.has(effective.name)) {
2411
+ throw new Error(`Duplicate composed tool name: ${effective.name}`);
2412
+ }
2413
+ seen.add(effective.name);
2414
+ tools.push(effective);
2415
+ }
2416
+ return { tools, names: tools.map((tool) => tool.name) };
2417
+ }
2418
+ };
2419
+ return builder;
2420
+ }
2421
+ // src/tools/tool-logger.ts
2422
+ function createToolLogger(config = {}) {
2423
+ const log = config.log ?? ((line) => console.error(line));
2424
+ return {
2425
+ afterToolCall: ({ toolName, result, durationMs, context, endpoint }) => {
2426
+ const record = {
2427
+ tool: toolName,
2428
+ service: endpoint.serviceName,
2429
+ action: endpoint.key,
2430
+ ok: result.ok,
2431
+ code: result.ok ? undefined : result.code,
2432
+ durationMs: Math.round(durationMs),
2433
+ source: String(context.source),
2434
+ traceId: getTraceId()
2435
+ };
2436
+ const codePart = result.ok ? "" : ` ${result.code}`;
2437
+ log(`[tool] ${result.ok ? "ok" : "warn"} ${toolName} (${endpoint.serviceName}.${endpoint.key})${codePart} ${record.durationMs}ms`);
2438
+ config.onRecord?.(record);
2439
+ }
2440
+ };
2441
+ }
2442
+ // src/tools/toolkit.ts
2443
+ function createToolkit() {
2444
+ return {
2445
+ mountMcp: (server, services, config) => mountMcp(server, services, config),
2446
+ mountAgent: (services, config) => mountAgent(services, config),
2447
+ buildMcpServer: (config, auth) => buildMcpServer(config, auth),
2448
+ createMcpHandler: (config) => createMcpHandler(config),
2449
+ createStdioMcpServer: (config) => createStdioMcpServer(config),
2450
+ createCli: (config) => createCli(config)
2451
+ };
2452
+ }
2453
+ // src/tools/transfer/download-core.ts
2454
+ import { basename, extname } from "node:path";
2455
+ var DEFAULT_MAX_BYTES = 100 * 1024 * 1024;
2456
+ var MIME_EXT = {
2457
+ "image/png": ".png",
2458
+ "image/jpeg": ".jpg",
2459
+ "image/webp": ".webp",
2460
+ "image/gif": ".gif",
2461
+ "video/mp4": ".mp4",
2462
+ "video/webm": ".webm",
2463
+ "audio/mpeg": ".mp3",
2464
+ "audio/wav": ".wav",
2465
+ "audio/ogg": ".ogg"
2466
+ };
2467
+
2468
+ class DownloadOperationError extends Error {
2469
+ code;
2470
+ status;
2471
+ constructor(code, message, status) {
2472
+ super(message);
2473
+ this.code = code;
2474
+ this.status = status;
2475
+ this.name = "DownloadOperationError";
2476
+ }
2477
+ }
2478
+ function extensionFor(url, mime) {
2479
+ if (MIME_EXT[mime])
2480
+ return MIME_EXT[mime];
2481
+ try {
2482
+ const ext = extname(new URL(url).pathname).toLowerCase();
2483
+ if (ext)
2484
+ return ext;
2485
+ } catch {}
2486
+ return ".bin";
2487
+ }
2488
+ function baseNameFor(url) {
2489
+ try {
2490
+ const path = new URL(url).pathname;
2491
+ return (basename(path, extname(path)) || "download").slice(0, 60);
2492
+ } catch {
2493
+ return "download";
2494
+ }
2495
+ }
2496
+ async function runDownloadOperation(config) {
2497
+ const res = await fetchGuarded(new URL(config.url), config.allowPrivateHosts ?? false, {
2498
+ timeoutMs: config.timeoutMs,
2499
+ signal: config.signal
2500
+ });
2501
+ if (!res.ok) {
2502
+ throw new DownloadOperationError("DOWNLOAD_HTTP_ERROR", `HTTP ${res.status}`, 502);
2503
+ }
2504
+ const mimeType = mediaTypeEssence(res.headers.get("content-type")) || "application/octet-stream";
2505
+ const max = config.maxBytes ?? DEFAULT_MAX_BYTES;
2506
+ const declared = Number(res.headers.get("content-length") ?? 0);
2507
+ if (declared > max) {
2508
+ await res.body?.cancel();
2509
+ throw new DownloadOperationError("DOWNLOAD_TOO_LARGE", `file exceeds the ${max}-byte cap`, 413);
2510
+ }
2511
+ const path = config.path ?? `${baseNameFor(config.url)}${extensionFor(config.url, mimeType)}`;
2512
+ return config.files.write(path, res.body ?? new Uint8Array, {
2513
+ maxBytes: max,
2514
+ mediaType: mimeType,
2515
+ signal: config.signal
2516
+ });
2517
+ }
2518
+
2519
+ // src/tools/transfer/managed-file-error.ts
2520
+ var SAFE_MANAGED_FILE_MESSAGES = {
2521
+ FILE_INVALID_PATH: "Invalid managed-file path",
2522
+ FILE_OUTSIDE_ROOT: "Managed-file path escapes its boundary",
2523
+ FILE_NOT_FOUND: "Managed file not found",
2524
+ FILE_NOT_REGULAR: "Managed path is not a regular file",
2525
+ FILE_INSPECTION_REJECTED: "Managed file rejected by inspection",
2526
+ FILE_TOO_LARGE: "Managed file exceeds the configured size limit",
2527
+ FILE_EXISTS: "Managed file already exists"
2528
+ };
2529
+ function managedFileAppError(error) {
2530
+ if (!(error instanceof ManagedFileError))
2531
+ return null;
2532
+ switch (error.code) {
2533
+ case "FILE_INVALID_PATH":
2534
+ case "FILE_OUTSIDE_ROOT":
2535
+ case "FILE_NOT_FOUND":
2536
+ case "FILE_NOT_REGULAR":
2537
+ case "FILE_INSPECTION_REJECTED":
2538
+ case "FILE_TOO_LARGE":
2539
+ case "FILE_EXISTS":
2540
+ return new AppError(error.code, SAFE_MANAGED_FILE_MESSAGES[error.code], STITCH_ERROR_STATUS[error.code]);
2541
+ case "FILE_IO_ERROR":
2542
+ return null;
2543
+ }
2544
+ }
2545
+ function normalizeFileToolError(error) {
2546
+ return managedFileAppError(error) ?? normalizeError(error);
2547
+ }
2548
+
2549
+ // src/tools/transfer/define-download-tool.ts
2550
+ function defineDownloadTool(config) {
2551
+ return defineRuntimeTool({
2552
+ name: config.name ?? "download",
2553
+ description: config.description,
2554
+ identity: managedNativeIdentity(config.identity, "POST"),
2555
+ input: config.input,
2556
+ output: ManagedFileRefSchema,
2557
+ transports: config.transports,
2558
+ annotations: config.annotations,
2559
+ present: config.present,
2560
+ handler: async (context) => {
2561
+ const url = await config.resolveUrl(context.input, context);
2562
+ if (!url) {
2563
+ throw new AppError("DOWNLOAD_NOT_FOUND", "Nothing to download", 404);
2564
+ }
2565
+ try {
2566
+ return await runDownloadOperation({
2567
+ url,
2568
+ files: config.files,
2569
+ path: config.pathFromInput?.(context.input),
2570
+ allowPrivateHosts: config.allowPrivateHosts,
2571
+ maxBytes: config.maxBytes,
2572
+ timeoutMs: config.timeoutMs,
2573
+ signal: context.signal
2574
+ });
2575
+ } catch (error) {
2576
+ if (error instanceof DownloadOperationError) {
2577
+ throw new AppError(error.code, `Download failed: ${error.message}`, error.status);
2578
+ }
2579
+ const managedError = managedFileAppError(error);
2580
+ if (managedError)
2581
+ throw managedError;
2582
+ throw error;
2583
+ }
2584
+ }
2585
+ });
2586
+ }
2587
+ // src/tools/transfer/define-upload-tool.ts
2588
+ import { z as z6 } from "zod";
2589
+
2590
+ // src/tools/transfer/upload-core.ts
2591
+ function runUploadOperation(files, path, upload, signal) {
2592
+ signal?.throwIfAborted();
2593
+ return files.read(path, { signal }).then((source) => upload(source, signal));
2594
+ }
2595
+
2596
+ // src/tools/transfer/define-upload-tool.ts
2597
+ var UploadToolInputSchema = z6.object({
2598
+ path: ManagedFilePathSchema.describe("Path relative to the configured file boundary")
2599
+ });
2600
+ function defineUploadTool(config) {
2601
+ return defineRuntimeTool({
2602
+ name: config.name ?? "upload",
2603
+ description: config.description,
2604
+ identity: managedNativeIdentity(config.identity, "POST"),
2605
+ input: UploadToolInputSchema,
2606
+ output: config.output,
2607
+ transports: config.transports,
2608
+ annotations: config.annotations,
2609
+ present: config.present,
2610
+ handler: async (context) => {
2611
+ try {
2612
+ return await runUploadOperation(config.files, context.input.path, (source) => config.upload(source, context), context.signal);
2613
+ } catch (error) {
2614
+ const managedError = managedFileAppError(error);
2615
+ if (managedError)
2616
+ throw managedError;
2617
+ throw error;
2618
+ }
2619
+ }
2620
+ });
2621
+ }
2622
+ // src/tools/transfer/view-file.ts
2623
+ import { extname as extname2 } from "node:path";
2624
+ var MAX_INLINE_BYTES = 20 * 1024 * 1024;
2625
+ var EXT_MIME = {
2626
+ ".png": "image/png",
2627
+ ".jpg": "image/jpeg",
2628
+ ".jpeg": "image/jpeg",
2629
+ ".gif": "image/gif",
2630
+ ".webp": "image/webp",
2631
+ ".mp3": "audio/mpeg",
2632
+ ".wav": "audio/wav",
2633
+ ".ogg": "audio/ogg",
2634
+ ".m4a": "audio/mp4",
2635
+ ".mp4": "video/mp4",
2636
+ ".webm": "video/webm",
2637
+ ".mov": "video/quicktime"
2638
+ };
2639
+ async function fetchSource(pathOrUrl, options, maxBytes) {
2640
+ const extMime = EXT_MIME[extname2(pathOrUrl).toLowerCase()];
2641
+ if (pathOrUrl.startsWith("http://") || pathOrUrl.startsWith("https://")) {
2642
+ const url = new URL(pathOrUrl);
2643
+ const res = await fetchGuarded(url, options.allowPrivateHosts ?? false, {
2644
+ timeoutMs: options.timeoutMs,
2645
+ signal: options.signal
2646
+ });
2647
+ if (!res.ok)
2648
+ throw new AppError("VIEW_HTTP_ERROR", `HTTP ${res.status}`, 502);
2649
+ const headerMime = mediaTypeEssence(res.headers.get("content-type"));
2650
+ const mimeType = headerMime || extMime || "application/octet-stream";
2651
+ if (mimeType.startsWith("video/")) {
2652
+ await res.body?.cancel();
2653
+ return { video: true, mimeType, bytesRead: 0 };
2654
+ }
2655
+ const declared = Number(res.headers.get("content-length") ?? 0);
2656
+ if (declared > maxBytes) {
2657
+ await res.body?.cancel();
2658
+ return { tooLarge: true, mimeType, bytesRead: 0 };
2659
+ }
2660
+ const buffer = await readCapped(res, maxBytes);
2661
+ return buffer ? { buffer, mimeType, bytesRead: buffer.length } : { tooLarge: true, mimeType, bytesRead: maxBytes };
2662
+ }
2663
+ if (!options.files) {
2664
+ throw new AppError("FILE_INVALID_PATH", "local file paths are disabled — set files to allow them", 400);
2665
+ }
2666
+ options.signal?.throwIfAborted();
2667
+ if (!extMime) {
2668
+ throw new AppError("FILE_INSPECTION_REJECTED", "refusing to read a non-media file", 422);
2669
+ }
2670
+ try {
2671
+ const source = await options.files.read(pathOrUrl, {
2672
+ maxBytes,
2673
+ signal: options.signal
2674
+ });
2675
+ const buffer = Buffer.from(source.bytes);
2676
+ return {
2677
+ buffer,
2678
+ mimeType: source.ref.mediaType ?? extMime,
2679
+ bytesRead: buffer.length
2680
+ };
2681
+ } catch (error) {
2682
+ if (error instanceof ManagedFileError && error.code === "FILE_TOO_LARGE") {
2683
+ return { tooLarge: true, mimeType: extMime, bytesRead: maxBytes };
2684
+ }
2685
+ throw error;
2686
+ }
2687
+ }
2688
+ async function resolveMediaWithinBudget(pathOrUrl, options, maxBytes) {
2689
+ if (maxBytes <= 0) {
2690
+ return {
2691
+ content: [
2692
+ { type: "text", text: `[media] total inline budget exhausted — ${pathOrUrl}` }
2693
+ ],
2694
+ bytes: 0
2695
+ };
2696
+ }
2697
+ const extMime = EXT_MIME[extname2(pathOrUrl).toLowerCase()];
2698
+ if (extMime?.startsWith("video/")) {
2699
+ return {
2700
+ content: [{ type: "text", text: `[video] ${extMime} — ${pathOrUrl}` }],
2701
+ bytes: 0
2702
+ };
2703
+ }
2704
+ const result = await fetchSource(pathOrUrl, options, maxBytes);
2705
+ if ("video" in result) {
2706
+ return {
2707
+ content: [{ type: "text", text: `[video] ${result.mimeType} — ${pathOrUrl}` }],
2708
+ bytes: result.bytesRead
2709
+ };
2710
+ }
2711
+ if ("tooLarge" in result) {
2712
+ return {
2713
+ content: [
2714
+ { type: "text", text: `[${result.mimeType}] too large to inline — ${pathOrUrl}` }
2715
+ ],
2716
+ bytes: result.bytesRead
2717
+ };
2718
+ }
2719
+ const { buffer, mimeType } = result;
2720
+ const sizeKb = (buffer.length / 1024).toFixed(0);
2721
+ if (mimeType.startsWith("image/")) {
2722
+ return {
2723
+ content: [
2724
+ {
2725
+ type: "image",
2726
+ data: buffer.toString("base64"),
2727
+ mimeType,
2728
+ annotations: { audience: ["user", "assistant"], priority: 0.9 }
2729
+ },
2730
+ { type: "text", text: `[image] ${mimeType}, ${sizeKb}KB` }
2731
+ ],
2732
+ bytes: buffer.length
2733
+ };
2734
+ }
2735
+ if (mimeType.startsWith("audio/")) {
2736
+ return {
2737
+ content: [
2738
+ {
2739
+ type: "audio",
2740
+ data: buffer.toString("base64"),
2741
+ mimeType,
2742
+ annotations: { audience: ["user", "assistant"], priority: 0.9 }
2743
+ },
2744
+ { type: "text", text: `[audio] ${mimeType}, ${sizeKb}KB` }
2745
+ ],
2746
+ bytes: buffer.length
2747
+ };
2748
+ }
2749
+ return {
2750
+ content: [{ type: "text", text: `[${mimeType}] ${sizeKb}KB — ${pathOrUrl}` }],
2751
+ bytes: buffer.length
2752
+ };
2753
+ }
2754
+ async function resolveMedia(pathOrUrl, options = {}) {
2755
+ return (await resolveMediaWithinBudget(pathOrUrl, options, MAX_INLINE_BYTES)).content;
2756
+ }
2757
+ async function runViewFileOperation(paths, options = {}, signal) {
2758
+ const list = Array.isArray(paths) ? paths : [paths];
2759
+ const content = [];
2760
+ const errors = [];
2761
+ let remainingBytes = MAX_INLINE_BYTES;
2762
+ for (const pathOrUrl of list) {
2763
+ signal?.throwIfAborted();
2764
+ try {
2765
+ const resolved = await resolveMediaWithinBudget(pathOrUrl, { ...options, signal }, remainingBytes);
2766
+ remainingBytes -= resolved.bytes;
2767
+ content.push(...resolved.content);
2768
+ } catch (error) {
2769
+ if (signal?.aborted)
2770
+ throw signal.reason ?? error;
2771
+ const message = normalizeFileToolError(error).message;
2772
+ errors.push({ path: pathOrUrl, message });
2773
+ content.push({ type: "text", text: `[${pathOrUrl}] Error: ${message}` });
2774
+ }
2775
+ }
2776
+ return ViewFileOutputSchema.parse({ content, errors });
2777
+ }
2778
+ function mountViewFile(server, options = {}) {
2779
+ server.registerTool("view_file", {
2780
+ description: "View media (image, audio, video) by URL or local path — returns it as content you can SEE / HEAR. Pass several paths to view multiple files at once. Use it on a generation `output` url to inspect the result.",
2781
+ inputSchema: ViewFileInputSchema.shape,
2782
+ annotations: { title: "View Media", readOnlyHint: true, idempotentHint: true }
2783
+ }, async (args) => {
2784
+ const result = await runViewFileOperation(args.paths, options);
2785
+ return { content: result.content };
2786
+ });
2787
+ }
2788
+
2789
+ // src/tools/transfer/define-view-file-tool.ts
2790
+ function defineViewFileTool(config) {
2791
+ const defaults = {
2792
+ mcp: (output) => ({ content: output.content }),
2793
+ agent: (output) => ({
2794
+ type: "content",
2795
+ value: output.content.map((part) => {
2796
+ if (part.type === "text")
2797
+ return part;
2798
+ return {
2799
+ type: "file",
2800
+ data: { type: "data", data: part.data },
2801
+ mediaType: part.mimeType
2802
+ };
2803
+ })
2804
+ })
2805
+ };
2806
+ return defineRuntimeTool({
2807
+ name: config.name ?? "view_file",
2808
+ description: config.description,
2809
+ identity: managedNativeIdentity(config.identity, "GET"),
2810
+ input: ViewFileInputSchema,
2811
+ output: ViewFileOutputSchema,
2812
+ transports: config.transports,
2813
+ annotations: config.annotations ?? {
2814
+ title: "View Media",
2815
+ readOnlyHint: true,
2816
+ idempotentHint: true
2817
+ },
2818
+ present: { ...defaults, ...config.present },
2819
+ handler: (context) => runViewFileOperation(context.input.paths, {
2820
+ files: config.files,
2821
+ allowPrivateHosts: config.allowPrivateHosts,
2822
+ timeoutMs: config.timeoutMs
2823
+ }, context.signal)
2824
+ });
2825
+ }
2826
+ // src/tools/transfer/mount-download.ts
2827
+ import { z as z7 } from "zod";
2828
+ function mountDownload(server, config) {
2829
+ const name = config.name ?? "download";
2830
+ assertToolName(name, "<native>", "download");
2831
+ server.registerTool(name, { description: config.description, inputSchema: z7.object(config.inputSchema) }, async (rawArgs) => {
2832
+ const args = isRecord(rawArgs) ? rawArgs : {};
2833
+ try {
2834
+ const url = await config.resolveUrl(args);
2835
+ if (!url)
2836
+ return textResult("Nothing to download.", true);
2837
+ const result = await runDownloadOperation({
2838
+ url,
2839
+ files: config.files,
2840
+ path: config.pathFromArgs?.(args),
2841
+ allowPrivateHosts: config.allowPrivateHosts,
2842
+ maxBytes: config.maxBytes,
2843
+ timeoutMs: config.timeoutMs
2844
+ });
2845
+ return textResult(JSON.stringify(result, null, 2));
2846
+ } catch (error) {
2847
+ if (error instanceof DownloadOperationError) {
2848
+ return textResult(`Download failed [${error.code}]: ${error.message}`, true);
2849
+ }
2850
+ const normalized = normalizeFileToolError(error);
2851
+ return textResult(`Download failed [${normalized.code}]: ${normalized.message}`, true);
2852
+ }
2853
+ });
2854
+ }
2855
+ // src/tools/transfer/mount-upload.ts
2856
+ function mountUpload(server, config) {
2857
+ const name = config.name ?? "upload";
2858
+ assertToolName(name, "<native>", "upload");
2859
+ server.registerTool(name, {
2860
+ description: config.description,
2861
+ inputSchema: {
2862
+ path: ManagedFilePathSchema.describe("Path relative to the configured file boundary")
2863
+ }
2864
+ }, async (rawArgs) => {
2865
+ const args = isRecord(rawArgs) ? rawArgs : {};
2866
+ const path = typeof args.path === "string" ? args.path : "";
2867
+ if (!path)
2868
+ return textResult("Provide `path`.", true);
2869
+ try {
2870
+ const uploaded = await runUploadOperation(config.files, path, config.upload);
2871
+ return textResult(JSON.stringify(uploaded ?? null, null, 2));
2872
+ } catch (error) {
2873
+ const normalized = normalizeFileToolError(error);
2874
+ return textResult(`Upload failed [${normalized.code}]: ${normalized.message}`, true);
2875
+ }
2876
+ });
2877
+ }
2878
+ // src/tools/transports.ts
2879
+ function emptyCounts() {
2880
+ return { HTTP: 0, MCP: 0, AGENT: 0, CLI: 0 };
2881
+ }
2882
+ function contractCounts(service) {
2883
+ const counts = emptyCounts();
2884
+ for (const method of Object.values(service.methods)) {
2885
+ if (!method.expose || method.expose.includes("HTTP"))
2886
+ counts.HTTP += 1;
2887
+ }
2888
+ for (const transport of TOOL_TRANSPORTS) {
2889
+ counts[transport] = collectToolSurface({
2890
+ surface: { services: [service] },
2891
+ transport,
2892
+ assertNames: false,
2893
+ assertUniqueNames: false
2894
+ }).length;
2895
+ }
2896
+ return counts;
2897
+ }
2898
+ function runtimeCounts(runtimeTools) {
2899
+ const counts = emptyCounts();
2900
+ for (const transport of TOOL_TRANSPORTS) {
2901
+ counts[transport] = collectToolSurface({
2902
+ surface: { runtimeTools },
2903
+ transport,
2904
+ assertNames: false,
2905
+ assertUniqueNames: false
2906
+ }).length;
2907
+ }
2908
+ return counts;
2909
+ }
2910
+ function addCounts(target, source) {
2911
+ for (const transport of ALL_TRANSPORTS)
2912
+ target[transport] += source[transport];
2913
+ }
2914
+ function summarizeTransports(surface) {
2915
+ const totals = emptyCounts();
2916
+ const sources = [];
2917
+ for (const service of surface.services ?? []) {
2918
+ const counts = contractCounts(service);
2919
+ addCounts(totals, counts);
2920
+ sources.push({ kind: "contract", service: service.name, counts });
2921
+ }
2922
+ const runtimeGroups = new Map;
2923
+ for (const definition of surface.runtimeTools ?? []) {
2924
+ const service = definition.identity.serviceName;
2925
+ const group = runtimeGroups.get(service);
2926
+ if (group)
2927
+ group.push(definition);
2928
+ else
2929
+ runtimeGroups.set(service, [definition]);
2930
+ }
2931
+ for (const [service, runtimeTools] of runtimeGroups) {
2932
+ const counts = runtimeCounts(runtimeTools);
2933
+ addCounts(totals, counts);
2934
+ sources.push({ kind: "runtime", service, counts });
2935
+ }
2936
+ return {
2937
+ contractServices: surface.services?.length ?? 0,
2938
+ runtimeTools: surface.runtimeTools?.length ?? 0,
2939
+ totals,
2940
+ sources
2941
+ };
2942
+ }
2943
+ export {
2944
+ wwwAuthenticateHeader,
2945
+ validateMcpSchemas,
2946
+ summarizeTransports,
2947
+ resolveMedia,
2948
+ readMcpCatalogStamp,
2949
+ protectedResourceMetadataUrl,
2950
+ oauthProtectedResourceRoute,
2951
+ mountWait,
2952
+ mountViewFile,
2953
+ mountUpload,
2954
+ mountOAuthProvider,
2955
+ mountMcpResource,
2956
+ mountMcp,
2957
+ mountDownload,
2958
+ mountAgent,
2959
+ mcpCatalogMeta,
2960
+ listToolNames,
2961
+ listContractToolNames,
2962
+ isToolExecutionControlError,
2963
+ isAgentToolError,
2964
+ inlineMcpAppBundle,
2965
+ flattenToolJsonSchema,
2966
+ findUntypedProperties,
2967
+ findNonPortableFormats,
2968
+ describeToolCatalog,
2969
+ defineWaitTool,
2970
+ defineViewFileTool,
2971
+ defineUploadTool,
2972
+ defineToolRegistry,
2973
+ defineRuntimeTool,
2974
+ defineDownloadTool,
2975
+ defineAsyncOperationContract,
2976
+ defineAsyncOperation,
2977
+ createToolkit,
2978
+ createToolLogger,
2979
+ createToolInvoker,
2980
+ createStdioMcpServer,
2981
+ createSecureClientMetadataFetcher,
2982
+ createRuntimeToolFactory,
2983
+ createMcpHttpRoute,
2984
+ createMcpHandler,
2985
+ createLocalStepDurability,
2986
+ createAsyncOperationSnapshotSchema,
2987
+ composeToolLifecycle,
2988
+ collectTools,
2989
+ coerceJsonArgs,
2990
+ buildToolManifest,
2991
+ buildMcpServer,
2992
+ bindStdioProcessSignals,
2993
+ bindContractAsyncOperation,
2994
+ ViewFileOutputSchema,
2995
+ ViewFileInputSchema,
2996
+ ViewFileErrorSchema,
2997
+ UploadToolInputSchema,
2998
+ ToolExecutionControlError,
2999
+ RESOURCE_MIME_TYPE,
3000
+ PROTECTED_RESOURCE_PATH,
3001
+ PORTABLE_JSON_SCHEMA_FORMATS,
3002
+ McpMediaContentSchema,
3003
+ McpAnnotationsSchema,
3004
+ MCP_CATALOG_META_KEY,
3005
+ EffectUnresolvedError,
3006
+ EXT_APPS_BUNDLE_PLACEHOLDER,
3007
+ AsyncOperationCancelResultSchema,
3008
+ AgentToolError
3009
+ };