stitchkit 0.136.7 → 0.137.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (358) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/dist/agent-runtime/stores/branch-observations.d.ts +19 -19
  3. package/dist/agent-runtime/stores/schedule-contract.d.ts.map +1 -1
  4. package/dist/agent-runtime/stores/schedule-records.d.ts.map +1 -1
  5. package/dist/agent-runtime/stores/schedule-tools.d.ts.map +1 -1
  6. package/dist/agent-runtime/stores/sql-rows.d.ts +36 -36
  7. package/dist/agent-runtime/terminal-commit.d.ts +5 -5
  8. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts +52 -52
  9. package/dist/agent-runtime/testing/store-conformance-support.d.ts +26 -26
  10. package/dist/browser/client-executors.d.ts +2 -3
  11. package/dist/browser/client-executors.d.ts.map +1 -1
  12. package/dist/browser/realtime-client.d.ts +6 -1
  13. package/dist/browser/realtime-client.d.ts.map +1 -1
  14. package/dist/browser/socket-io-client.d.ts.map +1 -1
  15. package/dist/browser/socket-io-contract.d.ts +2 -0
  16. package/dist/browser/socket-io-contract.d.ts.map +1 -1
  17. package/dist/contract/define-validation.d.ts +6 -0
  18. package/dist/contract/define-validation.d.ts.map +1 -1
  19. package/dist/contract/define.d.ts +1 -1
  20. package/dist/contract/define.d.ts.map +1 -1
  21. package/dist/contract/error-mapping.d.ts +71 -0
  22. package/dist/contract/error-mapping.d.ts.map +1 -0
  23. package/dist/contract/errors.d.ts +8 -0
  24. package/dist/contract/errors.d.ts.map +1 -1
  25. package/dist/contract/factory.d.ts +8 -0
  26. package/dist/contract/factory.d.ts.map +1 -1
  27. package/dist/contract/fragments.d.ts +45 -0
  28. package/dist/contract/fragments.d.ts.map +1 -0
  29. package/dist/contract/normalize.d.ts +6 -3
  30. package/dist/contract/normalize.d.ts.map +1 -1
  31. package/dist/contract/operation-read.d.ts +38 -0
  32. package/dist/contract/operation-read.d.ts.map +1 -0
  33. package/dist/contract/stream.d.ts.map +1 -1
  34. package/dist/contract/time-zone.d.ts +31 -0
  35. package/dist/contract/time-zone.d.ts.map +1 -0
  36. package/dist/contract/tool-options.d.ts +1 -1
  37. package/dist/contract/tool-options.d.ts.map +1 -1
  38. package/dist/device-relay/hub.d.ts +1 -1
  39. package/dist/device-relay/hub.d.ts.map +1 -1
  40. package/dist/entrypoints/agent-executor/acp.js +9 -9
  41. package/dist/entrypoints/agent-executor/claude-sdk.js +11 -11
  42. package/dist/entrypoints/agent-executor/claude.js +8 -8
  43. package/dist/entrypoints/agent-executor/codex.js +15 -15
  44. package/dist/entrypoints/agent-executor/testing.js +11 -11
  45. package/dist/entrypoints/agent-executor.js +14 -13
  46. package/dist/entrypoints/agent-runtime/ai-sdk.js +5 -5
  47. package/dist/entrypoints/agent-runtime/anthropic.js +1 -1
  48. package/dist/entrypoints/agent-runtime/browser.js +5 -5
  49. package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
  50. package/dist/entrypoints/agent-runtime/harness.js +14 -15
  51. package/dist/entrypoints/agent-runtime/openai.js +1 -1
  52. package/dist/entrypoints/agent-runtime/openrouter.js +7 -7
  53. package/dist/entrypoints/agent-runtime/postgres.js +5 -5
  54. package/dist/entrypoints/agent-runtime/realtime.js +8 -8
  55. package/dist/entrypoints/agent-runtime/sandbox.js +7 -7
  56. package/dist/entrypoints/agent-runtime/sqlite/bun.js +6 -6
  57. package/dist/entrypoints/agent-runtime/sqlite/node.js +6 -6
  58. package/dist/entrypoints/agent-runtime/testing.js +5 -5
  59. package/dist/entrypoints/agent-runtime.js +33 -29
  60. package/dist/entrypoints/application/diagnostic-journal.js +3 -3
  61. package/dist/entrypoints/application/directory-inbox.js +1 -1
  62. package/dist/entrypoints/application/grammy.js +1 -1
  63. package/dist/entrypoints/application/opentelemetry.js +2 -2
  64. package/dist/entrypoints/application.js +10 -10
  65. package/dist/entrypoints/cli/publish.d.ts +4 -4
  66. package/dist/entrypoints/cli/publish.d.ts.map +1 -1
  67. package/dist/entrypoints/cli/publish.js +160 -52
  68. package/dist/entrypoints/cli.d.ts +3 -1
  69. package/dist/entrypoints/cli.d.ts.map +1 -1
  70. package/dist/entrypoints/cli.js +520 -59
  71. package/dist/entrypoints/contract.d.ts +5 -1
  72. package/dist/entrypoints/contract.d.ts.map +1 -1
  73. package/dist/entrypoints/contract.js +25 -7
  74. package/dist/entrypoints/device-relay.js +20 -10
  75. package/dist/entrypoints/files/packaging.js +2 -2
  76. package/dist/entrypoints/files.js +10 -10
  77. package/dist/entrypoints/handler.d.ts +1 -1
  78. package/dist/entrypoints/handler.d.ts.map +1 -1
  79. package/dist/entrypoints/handler.js +12 -12
  80. package/dist/entrypoints/http.js +13 -12
  81. package/dist/entrypoints/index.js +36 -18
  82. package/dist/entrypoints/live.d.ts +2 -1
  83. package/dist/entrypoints/live.d.ts.map +1 -1
  84. package/dist/entrypoints/live.js +630 -1
  85. package/dist/entrypoints/node.d.ts +5 -0
  86. package/dist/entrypoints/node.d.ts.map +1 -1
  87. package/dist/entrypoints/node.js +36 -16
  88. package/dist/entrypoints/observability.js +25 -10
  89. package/dist/entrypoints/postgres.d.ts +4 -1
  90. package/dist/entrypoints/postgres.d.ts.map +1 -1
  91. package/dist/entrypoints/postgres.js +312 -0
  92. package/dist/entrypoints/primitives.js +11 -4
  93. package/dist/entrypoints/process.js +7 -7
  94. package/dist/entrypoints/react.js +1 -1
  95. package/dist/entrypoints/realtime.js +3 -3
  96. package/dist/entrypoints/remote.js +6 -29
  97. package/dist/entrypoints/server.d.ts +6 -1
  98. package/dist/entrypoints/server.d.ts.map +1 -1
  99. package/dist/entrypoints/server.js +93 -32
  100. package/dist/entrypoints/service-host/macos.js +6 -6
  101. package/dist/entrypoints/service-host/work.js +6 -6
  102. package/dist/entrypoints/service-host.js +10 -10
  103. package/dist/entrypoints/spend.js +2 -1
  104. package/dist/entrypoints/sync.js +5 -5
  105. package/dist/entrypoints/telegram.js +8 -8
  106. package/dist/entrypoints/testing.d.ts +1 -0
  107. package/dist/entrypoints/testing.d.ts.map +1 -1
  108. package/dist/entrypoints/testing.js +1501 -13
  109. package/dist/entrypoints/tools/agent.js +6 -7
  110. package/dist/entrypoints/tools/connections.js +9 -11
  111. package/dist/entrypoints/tools/contract.js +1 -2
  112. package/dist/entrypoints/tools/invoker.js +4 -5
  113. package/dist/entrypoints/tools/mcp.js +10 -11
  114. package/dist/entrypoints/tools/toolkit.d.ts +1 -1
  115. package/dist/entrypoints/tools/toolkit.d.ts.map +1 -1
  116. package/dist/entrypoints/tools/toolkit.js +29 -24
  117. package/dist/entrypoints/tools.js +28 -30
  118. package/dist/entrypoints/tracking/contract.js +2 -1
  119. package/dist/entrypoints/xlsx.js +5 -8
  120. package/dist/{index-033tyx59.js → index-0zw0hcyg.js} +4 -1
  121. package/dist/{index-zcq3dby3.js → index-1bjwfnnj.js} +1 -1
  122. package/dist/{index-f103md2v.js → index-1cfacbe2.js} +88 -23
  123. package/dist/{index-gj4wdts6.js → index-1ckh9qx1.js} +1 -1
  124. package/dist/index-1pvwmbxp.js +1435 -0
  125. package/dist/{index-0s75mjh7.js → index-2e4hdh32.js} +1 -1
  126. package/dist/{index-3shdhzt6.js → index-2j0pqxkn.js} +12 -6
  127. package/dist/index-3k8w02se.js +28 -0
  128. package/dist/{index-7fjbdga8.js → index-3pb4ccj2.js} +8 -0
  129. package/dist/{index-w7e402wx.js → index-48kb4gqq.js} +46 -7
  130. package/dist/{index-cv9b7fz2.js → index-6rws2xf5.js} +8 -0
  131. package/dist/{index-bbpygynk.js → index-77w5vx0g.js} +1 -1
  132. package/dist/index-7dz1ngaf.js +35 -0
  133. package/dist/{index-y68gavb5.js → index-7n4atsm4.js} +1 -1
  134. package/dist/index-8ef1bfea.js +71 -0
  135. package/dist/{index-0x4mnwg5.js → index-8k3y9nd4.js} +6 -9
  136. package/dist/{index-ezwsqyad.js → index-8rkdkefj.js} +40 -23
  137. package/dist/{index-3cwq5byx.js → index-9nax7tkn.js} +2 -2
  138. package/dist/{index-dz6tstcp.js → index-9r6emjwz.js} +1 -1
  139. package/dist/{index-32ew02z1.js → index-c4b7d6ej.js} +5 -5
  140. package/dist/index-ceshyndf.js +284 -0
  141. package/dist/{index-w161azza.js → index-d13rw31w.js} +6 -6
  142. package/dist/{index-1h0dtfz3.js → index-dmm7vs3f.js} +1 -1
  143. package/dist/{index-ypm85xwe.js → index-dp8j2e77.js} +1 -1
  144. package/dist/{index-qqd979f7.js → index-edycjvrv.js} +9 -9
  145. package/dist/{index-18qdpbcq.js → index-egpf9dv0.js} +200 -1479
  146. package/dist/{index-fatke81t.js → index-ezgvsj9w.js} +2 -2
  147. package/dist/{index-chapre0y.js → index-f3e7tj1g.js} +1 -1
  148. package/dist/{index-df5xr2f9.js → index-frsd2a94.js} +16 -1
  149. package/dist/index-fy9mmek1.js +95 -0
  150. package/dist/{index-2331y2tf.js → index-g0gvfzrx.js} +12 -12
  151. package/dist/index-gpe8d1ka.js +19 -0
  152. package/dist/{index-4p2zx593.js → index-gyw4qd0m.js} +1 -1
  153. package/dist/index-gzqy81tw.js +172 -0
  154. package/dist/{index-yrhw10ef.js → index-h34c510q.js} +8 -4
  155. package/dist/{index-rr94xcj6.js → index-h527p1yj.js} +10 -4
  156. package/dist/{index-qj0sq69b.js → index-hgf1tbgz.js} +76 -16
  157. package/dist/{index-smvmnz5y.js → index-hvpan32x.js} +1 -1
  158. package/dist/{index-4gbybjg6.js → index-hxawqrb6.js} +2 -2
  159. package/dist/{index-0k1ba0ss.js → index-j91jffhv.js} +1 -1
  160. package/dist/{index-d01akj5n.js → index-jr4kwetx.js} +8 -8
  161. package/dist/{index-xqppqn97.js → index-ka6z48zc.js} +315 -69
  162. package/dist/{index-by8w2461.js → index-kw0segzt.js} +104 -3
  163. package/dist/{index-6f4fjygr.js → index-m5t4dr7h.js} +29 -7
  164. package/dist/{index-afaq0nc4.js → index-n0egp1ke.js} +1 -1
  165. package/dist/{index-9fzjgg86.js → index-n74rb1dq.js} +2 -2
  166. package/dist/{index-dwq6a6sq.js → index-pt25vmhc.js} +33 -16
  167. package/dist/{index-vwg0n3e6.js → index-pyazb8q4.js} +23 -14
  168. package/dist/{index-5md04mwc.js → index-qpjjbkc5.js} +4 -4
  169. package/dist/{index-08a3qfr8.js → index-r1qt6zgj.js} +1 -1
  170. package/dist/{index-ctaxjpa4.js → index-r709pqed.js} +1 -1
  171. package/dist/{index-2zrx0nzv.js → index-rzc40z6e.js} +3 -5
  172. package/dist/{index-gq35s3bm.js → index-s5axtd56.js} +2 -2
  173. package/dist/{index-edpkm3k7.js → index-scpcps66.js} +669 -16
  174. package/dist/{index-ry8m2mhg.js → index-sf2mt6wj.js} +1 -1
  175. package/dist/{index-tjhhsnjv.js → index-t1213r0t.js} +1 -1
  176. package/dist/{index-gvgtmt7a.js → index-t7efje30.js} +2 -2
  177. package/dist/{index-w3s79kcb.js → index-tzyk36dy.js} +1 -1
  178. package/dist/{index-8tn10tp6.js → index-v64bvwjr.js} +1 -1
  179. package/dist/{index-1fhbe4e4.js → index-vksbsqpb.js} +1 -1
  180. package/dist/{index-dxft2mnm.js → index-wdg7bswj.js} +1 -1
  181. package/dist/{index-ppy23bd2.js → index-wjx1zs2r.js} +7 -578
  182. package/dist/{index-efbzm2se.js → index-x2r0ma9t.js} +1 -1
  183. package/dist/{index-kd48gk7d.js → index-x8py72a3.js} +1 -1
  184. package/dist/index-xvydbxmk.js +1404 -0
  185. package/dist/index-xwaphv0d.js +31 -0
  186. package/dist/{index-a09r9ff0.js → index-y44j39yk.js} +1 -1
  187. package/dist/{index-7mjsb7zv.js → index-ybrrxjhb.js} +1 -1
  188. package/dist/{index-xsrma0jd.js → index-ysthxsa8.js} +6 -6
  189. package/dist/{index-6p5pshcd.js → index-yyh3ey4b.js} +1 -1
  190. package/dist/{index-mr3njw67.js → index-z6hq9j8j.js} +1 -1
  191. package/dist/{index-67mzzkdv.js → index-z72agxdn.js} +2 -2
  192. package/dist/{index-e4w0sfm1.js → index-z78mtc16.js} +1 -1
  193. package/dist/{index-7csn6pva.js → index-ze94h4ph.js} +5 -0
  194. package/dist/internal/json-stringify.d.ts +12 -0
  195. package/dist/internal/json-stringify.d.ts.map +1 -1
  196. package/dist/internal/unix-client-error.d.ts +4 -0
  197. package/dist/internal/unix-client-error.d.ts.map +1 -1
  198. package/dist/live/watch-contract.d.ts +4 -0
  199. package/dist/live/watch-contract.d.ts.map +1 -1
  200. package/dist/live/watch-fanout-frame.d.ts +81 -0
  201. package/dist/live/watch-fanout-frame.d.ts.map +1 -0
  202. package/dist/live/watch-fanout.d.ts +57 -0
  203. package/dist/live/watch-fanout.d.ts.map +1 -0
  204. package/dist/observability/audit.d.ts.map +1 -1
  205. package/dist/observability/spool-core.d.ts +1 -0
  206. package/dist/observability/spool-core.d.ts.map +1 -1
  207. package/dist/observability/spool-drain.d.ts +48 -0
  208. package/dist/observability/spool-drain.d.ts.map +1 -0
  209. package/dist/observability/spool.d.ts +12 -6
  210. package/dist/observability/spool.d.ts.map +1 -1
  211. package/dist/postgres/connection-config.d.ts +54 -0
  212. package/dist/postgres/connection-config.d.ts.map +1 -0
  213. package/dist/postgres/rollback-transaction.d.ts +61 -0
  214. package/dist/postgres/rollback-transaction.d.ts.map +1 -0
  215. package/dist/primitives/deadline.d.ts +4 -4
  216. package/dist/primitives/deadline.d.ts.map +1 -1
  217. package/dist/server/error-hook.d.ts +3 -32
  218. package/dist/server/error-hook.d.ts.map +1 -1
  219. package/dist/server/local-consent-key.d.ts +104 -0
  220. package/dist/server/local-consent-key.d.ts.map +1 -0
  221. package/dist/server/local-control-journal.d.ts +51 -0
  222. package/dist/server/local-control-journal.d.ts.map +1 -0
  223. package/dist/server/local-control-reporter.d.ts +32 -0
  224. package/dist/server/local-control-reporter.d.ts.map +1 -0
  225. package/dist/server/local-control.d.ts +48 -0
  226. package/dist/server/local-control.d.ts.map +1 -0
  227. package/dist/server/local-host-clients.d.ts +105 -0
  228. package/dist/server/local-host-clients.d.ts.map +1 -0
  229. package/dist/server/middleware/trust-fence.d.ts +20 -0
  230. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  231. package/dist/spend/receipt-spool.d.ts +9 -4
  232. package/dist/spend/receipt-spool.d.ts.map +1 -1
  233. package/dist/testing/tool-surface-checks.d.ts +89 -0
  234. package/dist/testing/tool-surface-checks.d.ts.map +1 -0
  235. package/dist/testing/tool-surface-cli-callable.d.ts +63 -0
  236. package/dist/testing/tool-surface-cli-callable.d.ts.map +1 -0
  237. package/dist/testing/tool-surface-dead-refs.d.ts +32 -0
  238. package/dist/testing/tool-surface-dead-refs.d.ts.map +1 -0
  239. package/dist/testing/tool-surface-gates.d.ts +72 -0
  240. package/dist/testing/tool-surface-gates.d.ts.map +1 -0
  241. package/dist/testing/tool-surface-parity-drivers.d.ts +56 -0
  242. package/dist/testing/tool-surface-parity-drivers.d.ts.map +1 -0
  243. package/dist/testing/tool-surface-parity.d.ts +28 -0
  244. package/dist/testing/tool-surface-parity.d.ts.map +1 -0
  245. package/dist/testing/tool-surface-ratchet.d.ts +71 -0
  246. package/dist/testing/tool-surface-ratchet.d.ts.map +1 -0
  247. package/dist/tools/agent-tools.d.ts +3 -0
  248. package/dist/tools/agent-tools.d.ts.map +1 -1
  249. package/dist/tools/cli/command.d.ts +3 -0
  250. package/dist/tools/cli/command.d.ts.map +1 -1
  251. package/dist/tools/cli/create-cli.d.ts.map +1 -1
  252. package/dist/tools/cli/distribution-config.d.ts +39 -1
  253. package/dist/tools/cli/distribution-config.d.ts.map +1 -1
  254. package/dist/tools/cli/distribution-routes.d.ts +4 -2
  255. package/dist/tools/cli/distribution-routes.d.ts.map +1 -1
  256. package/dist/tools/cli/format.d.ts +3 -6
  257. package/dist/tools/cli/format.d.ts.map +1 -1
  258. package/dist/tools/cli/invoke.d.ts +4 -0
  259. package/dist/tools/cli/invoke.d.ts.map +1 -1
  260. package/dist/tools/cli/local-key-command.d.ts +53 -0
  261. package/dist/tools/cli/local-key-command.d.ts.map +1 -0
  262. package/dist/tools/cli/managed-surface.d.ts.map +1 -1
  263. package/dist/tools/cli/publication-contract.d.ts +9 -2
  264. package/dist/tools/cli/publication-contract.d.ts.map +1 -1
  265. package/dist/tools/cli/publication.d.ts.map +1 -1
  266. package/dist/tools/cli/run-managed.d.ts.map +1 -1
  267. package/dist/tools/cli/run-stream.d.ts.map +1 -1
  268. package/dist/tools/cli/runner.d.ts +8 -3
  269. package/dist/tools/cli/runner.d.ts.map +1 -1
  270. package/dist/tools/cli/secret.d.ts +55 -0
  271. package/dist/tools/cli/secret.d.ts.map +1 -0
  272. package/dist/tools/cli/session.d.ts +2 -2
  273. package/dist/tools/cli/session.d.ts.map +1 -1
  274. package/dist/tools/cli/signature.d.ts +23 -9
  275. package/dist/tools/cli/signature.d.ts.map +1 -1
  276. package/dist/tools/cli/stream.d.ts.map +1 -1
  277. package/dist/tools/cli/unix-outcome.d.ts +6 -0
  278. package/dist/tools/cli/unix-outcome.d.ts.map +1 -1
  279. package/dist/tools/cli/update.d.ts +6 -1
  280. package/dist/tools/cli/update.d.ts.map +1 -1
  281. package/dist/tools/execute-result.d.ts +20 -0
  282. package/dist/tools/execute-result.d.ts.map +1 -1
  283. package/dist/tools/execute.d.ts +3 -0
  284. package/dist/tools/execute.d.ts.map +1 -1
  285. package/dist/tools/internal/json-projection.d.ts +13 -9
  286. package/dist/tools/internal/json-projection.d.ts.map +1 -1
  287. package/dist/tools/internal/remote-error.d.ts +15 -0
  288. package/dist/tools/internal/remote-error.d.ts.map +1 -0
  289. package/dist/tools/internal/surface-projector.d.ts +2 -0
  290. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  291. package/dist/tools/invoker.d.ts +3 -0
  292. package/dist/tools/invoker.d.ts.map +1 -1
  293. package/dist/tools/mcp/handler.d.ts.map +1 -1
  294. package/dist/tools/mcp/lazy-discovery.d.ts +2 -0
  295. package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -1
  296. package/dist/tools/mcp/mount.d.ts +5 -0
  297. package/dist/tools/mcp/mount.d.ts.map +1 -1
  298. package/dist/tools/mcp/register.d.ts +2 -0
  299. package/dist/tools/mcp/register.d.ts.map +1 -1
  300. package/dist/tools/mcp/runtime-tools.d.ts +2 -0
  301. package/dist/tools/mcp/runtime-tools.d.ts.map +1 -1
  302. package/dist/tools/mcp/stdio.d.ts.map +1 -1
  303. package/dist/tools/mount.d.ts +3 -0
  304. package/dist/tools/mount.d.ts.map +1 -1
  305. package/dist/tools/read-operation.d.ts +2 -6
  306. package/dist/tools/read-operation.d.ts.map +1 -1
  307. package/dist/tools/remote.d.ts.map +1 -1
  308. package/dist/tools/runtime-tool.d.ts.map +1 -1
  309. package/dist/tools/toolkit.d.ts +10 -3
  310. package/dist/tools/toolkit.d.ts.map +1 -1
  311. package/dist/xlsx/schema.d.ts.map +1 -1
  312. package/llms/cli-publish.txt +4 -1
  313. package/llms/cli.2.txt +42 -51
  314. package/llms/cli.3.txt +34 -1
  315. package/llms/cli.txt +18 -3
  316. package/llms/contract.txt +47 -5
  317. package/llms/handler.txt +1 -1
  318. package/llms/live.txt +82 -0
  319. package/llms/node.txt +5 -0
  320. package/llms/observability.2.txt +1 -1
  321. package/llms/observability.txt +6 -0
  322. package/llms/postgres.txt +14 -3
  323. package/llms/server.2.txt +206 -240
  324. package/llms/server.3.txt +242 -202
  325. package/llms/server.4.txt +202 -1025
  326. package/llms/server.5.txt +1053 -255
  327. package/llms/server.6.txt +274 -0
  328. package/llms/server.txt +32 -116
  329. package/llms/spend.txt +8 -7
  330. package/llms/stitchkit.2.txt +13 -35
  331. package/llms/stitchkit.3.txt +27 -0
  332. package/llms/stitchkit.txt +82 -82
  333. package/llms/testing.txt +40 -0
  334. package/llms/tools-toolkit.txt +2 -2
  335. package/llms/tools.2.txt +29 -20
  336. package/llms/{upgrading-0.128.0-0.129.0.txt → upgrading-0.128.0-0.131.0.txt} +101 -3
  337. package/llms/{upgrading-0.130.0-0.136.0.txt → upgrading-0.132.0-0.137.0.txt} +62 -101
  338. package/llms/upgrading.txt +2 -2
  339. package/llms-full.txt +641 -189
  340. package/llms.txt +14 -14
  341. package/package.json +3 -3
  342. package/dist/index-9118dw8d.js +0 -603
  343. package/dist/index-9vj869rx.js +0 -19
  344. package/dist/index-a1rjr381.js +0 -114
  345. package/dist/index-dacxr7nf.js +0 -17
  346. package/dist/index-dm50x3by.js +0 -63
  347. package/dist/index-dmrx8xma.js +0 -163
  348. package/dist/index-ednf2cxs.js +0 -37
  349. package/dist/{index-e4zt2x70.js → index-3czppvrr.js} +3 -3
  350. package/dist/{index-42n9jycn.js → index-3f79t32b.js} +3 -3
  351. package/dist/{index-mfe9a266.js → index-84n49vam.js} +0 -0
  352. package/dist/{index-f16b7rze.js → index-er1tp8de.js} +3 -3
  353. package/dist/{index-k137ezb6.js → index-f5d0fdcf.js} +3 -3
  354. package/dist/{index-65p8v81y.js → index-psz8qrz0.js} +3 -3
  355. package/dist/{index-kadgaw1s.js → index-r8cq86h1.js} +0 -0
  356. package/dist/{index-1yky29qg.js → index-tyyvbarf.js} +0 -0
  357. package/dist/{index-tjakdpf2.js → index-wq71v08n.js} +3 -3
  358. package/dist/{index-7an2fs5h.js → index-wswcpbm4.js} +3 -3
@@ -1,107 +1,75 @@
1
- import {
2
- STANDARD_STRING_FORMATS
3
- } from "./index-ha1tv70k.js";
4
1
  import {
5
2
  toJsonSchema,
6
3
  jsonSchemaFields
7
4
  } from "./index-d1pdv8qc.js";
8
- import {
9
- toolSurfaceOutputSchema,
10
- toToolName,
11
- assertUniqueToolName,
12
- buildToolPresentationSchema,
13
- projectedContractToolName
14
- } from "./index-edpkm3k7.js";
15
- import {
16
- unwrapZodWrappers,
17
- objectShapeKeys,
18
- mergeSchemas
19
- } from "./index-dm50x3by.js";
20
- import {
21
- jsonSchemaObjectCoercionMembers
22
- } from "./index-dsa676h8.js";
23
- import {
24
- coerceJsonArgs2
25
- } from "./index-qj0sq69b.js";
26
5
  import {
27
6
  isInspectOnlyLifecycle,
28
7
  inspectOnlyError,
29
8
  resolveOptionalCliToolAccess,
9
+ toolSurfaceOutputSchema,
30
10
  toolResultFromError,
11
+ applyToolErrorMapping,
12
+ canonicalToolErrorCode,
31
13
  toolErrorFromResult,
32
14
  toolCauseFromResult,
15
+ toToolName,
16
+ assertUniqueToolName,
17
+ buildToolPresentationSchema,
18
+ projectedContractToolName,
33
19
  createToolRunner,
34
20
  formatToolError
35
- } from "./index-9118dw8d.js";
36
- import {
37
- isRepeatableRead
38
- } from "./index-0x4mnwg5.js";
39
- import {
40
- MCP_FILE_NAME_META_KEY2,
41
- McpImageContentSchema,
42
- McpAudioContentSchema
43
- } from "./index-gy9x38a2.js";
44
- import {
45
- readContractStreamItems,
46
- contractStreamLifetimeExceeded
47
- } from "./index-yrhw10ef.js";
21
+ } from "./index-scpcps66.js";
48
22
  import {
49
- writeContainedFile
50
- } from "./index-rjs94dny.js";
51
- import {
52
- openPinnedDirectory,
53
- isSafeEntryName,
54
- containedEntryMetadata
55
- } from "./index-xrgn784x.js";
23
+ unwrapZodWrappers,
24
+ mergeSchemas,
25
+ coerceJsonArgs2
26
+ } from "./index-hgf1tbgz.js";
56
27
  import {
57
- pollUntil,
58
- mediaExtension
59
- } from "./index-mh3jdb25.js";
28
+ jsonSchemaObjectCoercionMembers
29
+ } from "./index-dsa676h8.js";
60
30
  import {
61
- fetchGuarded,
62
- readCapped
63
- } from "./index-dz6tstcp.js";
31
+ projectRemoteError
32
+ } from "./index-7dz1ngaf.js";
64
33
  import {
65
34
  projectJsonSafe,
66
35
  stringifyJsonSafe
67
- } from "./index-9vj869rx.js";
36
+ } from "./index-gzqy81tw.js";
68
37
  import {
69
38
  collectToolSurface
70
- } from "./index-2zrx0nzv.js";
39
+ } from "./index-rzc40z6e.js";
40
+ import {
41
+ assertErrorCodeMapping
42
+ } from "./index-fy9mmek1.js";
71
43
  import {
72
44
  validateDeclaredOutput
73
- } from "./index-dwq6a6sq.js";
45
+ } from "./index-pt25vmhc.js";
74
46
  import {
75
47
  assertNoLegacyTransports
76
48
  } from "./index-akfgymyr.js";
77
- import {
78
- HELP_SHOWN_KEYWORDS
79
- } from "./index-e413q2cj.js";
80
49
  import {
81
50
  isUnsafeKey,
82
51
  safeJsonParse
83
52
  } from "./index-zsarb5xp.js";
84
- import {
85
- errnoOf
86
- } from "./index-jj9228tt.js";
87
53
  import {
88
54
  formatZodError2
89
55
  } from "./index-1eeqpadm.js";
90
56
  import {
91
57
  AppError2,
92
58
  STITCH_ERROR_STATUS2
93
- } from "./index-7fjbdga8.js";
59
+ } from "./index-3pb4ccj2.js";
60
+ import {
61
+ ApiError2
62
+ } from "./index-kfjkb396.js";
94
63
  import {
95
64
  UNIX_CLIENT_TRANSPORT_ERROR_NAME,
96
65
  UNIX_CLIENT_TRANSPORT_ERROR_CODES,
97
66
  UNIX_CLIENT_DELIVERY_STATES
98
- } from "./index-cv9b7fz2.js";
67
+ } from "./index-6rws2xf5.js";
99
68
  import {
100
69
  assertPositiveSafeInteger
101
70
  } from "./index-gr0kxymw.js";
102
71
  import {
103
72
  isRecord,
104
- isAsyncIterable,
105
73
  transportResult
106
74
  } from "./index-ps3djm8d.js";
107
75
 
@@ -469,8 +437,20 @@ var DEFAULT_EXIT_CODES2 = {
469
437
  function cliExitCode2(result, exitCodes) {
470
438
  if (result.ok)
471
439
  return 0;
472
- const codes = { ...DEFAULT_EXIT_CODES2, ...exitCodes };
473
- return Object.hasOwn(codes, result.code) ? codes[result.code] ?? 1 : 1;
440
+ const canonical = canonicalToolErrorCode(result);
441
+ if (exitCodes !== undefined && Object.hasOwn(exitCodes, result.code)) {
442
+ return exitCodes[result.code] ?? 1;
443
+ }
444
+ if (exitCodes !== undefined && canonical !== result.code && Object.hasOwn(exitCodes, canonical)) {
445
+ return exitCodes[canonical] ?? 1;
446
+ }
447
+ if (Object.hasOwn(DEFAULT_EXIT_CODES2, result.code)) {
448
+ return DEFAULT_EXIT_CODES2[result.code] ?? 1;
449
+ }
450
+ if (canonical !== result.code && Object.hasOwn(DEFAULT_EXIT_CODES2, canonical)) {
451
+ return DEFAULT_EXIT_CODES2[canonical] ?? 1;
452
+ }
453
+ return 1;
474
454
  }
475
455
  function emitResult2(result, writers, opts) {
476
456
  if (result.ok) {
@@ -481,11 +461,12 @@ function emitResult2(result, writers, opts) {
481
461
  `);
482
462
  return 0;
483
463
  }
484
- const error = formatToolError(result, opts.toolName, opts.errorHint);
464
+ const mapped = applyToolErrorMapping(result, opts.errors);
465
+ const error = formatToolError(mapped, opts.toolName, opts.errorHint);
485
466
  const text = opts.json ? JSON.stringify(error) : JSON.stringify(error, null, 2);
486
467
  writers.stderr(`${text}
487
468
  `);
488
- return cliExitCode2(result, opts.exitCodes);
469
+ return cliExitCode2(mapped, opts.exitCodes);
489
470
  }
490
471
  function presentationFailureHint(repeatable, printed) {
491
472
  if (repeatable) {
@@ -497,6 +478,7 @@ function emitPresentationFailure(result, failure, writers, opts) {
497
478
  const printed = !opts.repeatable && result.data !== undefined;
498
479
  if (printed)
499
480
  emitResult2(result, writers, opts);
481
+ const mappedCause = applyToolErrorMapping(failure, opts.errors);
500
482
  return emitResult2({
501
483
  ok: false,
502
484
  code: "CLI_PRESENTATION_FAILED",
@@ -506,10 +488,130 @@ function emitPresentationFailure(result, failure, writers, opts) {
506
488
  command: opts.toolName,
507
489
  operationSucceeded: true,
508
490
  resultOnStdout: printed,
509
- cause: formatToolError(failure)
491
+ cause: formatToolError(mappedCause)
510
492
  },
511
493
  hint: presentationFailureHint(opts.repeatable, printed)
512
- }, writers, { json: opts.json, toolName: opts.toolName, exitCodes: opts.exitCodes });
494
+ }, writers, {
495
+ json: opts.json,
496
+ toolName: opts.toolName,
497
+ exitCodes: opts.exitCodes,
498
+ errors: opts.errors
499
+ });
500
+ }
501
+
502
+ // src/tools/cli/unix-outcome.ts
503
+ var MAX_CAUSE_DEPTH = 16;
504
+ var UNIX_ERROR_CODES = new Set(UNIX_CLIENT_TRANSPORT_ERROR_CODES);
505
+ var UNIX_DELIVERY_STATES = new Set(UNIX_CLIENT_DELIVERY_STATES);
506
+ function ownValue(value, key) {
507
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
508
+ return descriptor && "value" in descriptor ? descriptor.value : undefined;
509
+ }
510
+ function ownString(value, key) {
511
+ const found = ownValue(value, key);
512
+ return typeof found === "string" ? found : undefined;
513
+ }
514
+ function isUnixErrorCode(value) {
515
+ return value !== undefined && UNIX_ERROR_CODES.has(value);
516
+ }
517
+ function isUnixDeliveryState(value) {
518
+ return value !== undefined && UNIX_DELIVERY_STATES.has(value);
519
+ }
520
+ function findUnixTransportError(root) {
521
+ const visited = new Set;
522
+ let current = root;
523
+ for (let depth = 0;depth < MAX_CAUSE_DEPTH && current !== undefined; depth += 1) {
524
+ if (typeof current !== "object" || current === null || visited.has(current))
525
+ return;
526
+ visited.add(current);
527
+ if (current instanceof Error && ownString(current, "name") === UNIX_CLIENT_TRANSPORT_ERROR_NAME) {
528
+ const code = ownString(current, "code");
529
+ const delivery = ownString(current, "delivery");
530
+ if (isUnixErrorCode(code) && isUnixDeliveryState(delivery)) {
531
+ const inner = ownValue(current, "cause");
532
+ const causeCode = typeof inner === "object" && inner !== null ? ownString(inner, "code") : undefined;
533
+ const causePath = typeof inner === "object" && inner !== null ? ownString(inner, "path") : undefined;
534
+ const socketPath = ownString(current, "socketPath") ?? causePath;
535
+ const message = ownString(current, "message") ?? "";
536
+ return {
537
+ code,
538
+ delivery,
539
+ message,
540
+ ...causeCode !== undefined && { causeCode },
541
+ ...socketPath !== undefined && { socketPath }
542
+ };
543
+ }
544
+ }
545
+ current = ownValue(current, "cause");
546
+ }
547
+ return;
548
+ }
549
+ function notDispatchedMessage(found) {
550
+ if (found.code === "UNIX_CONNECT_FAILED") {
551
+ const target = found.socketPath ? `"${found.socketPath}"` : "the unix socket";
552
+ const suffix = found.causeCode ? ` (${found.causeCode})` : "";
553
+ return `Not executed: application is not listening on ${target}${suffix}`;
554
+ }
555
+ if (found.code === "UNIX_TARGET_REFUSED") {
556
+ return `Not executed: unix socket target refused — ${found.message}`;
557
+ }
558
+ return `Not executed: ${found.message}`;
559
+ }
560
+ function notDispatchedHint(code) {
561
+ if (code === "UNIX_CONNECT_FAILED") {
562
+ return "The request was not executed because the application is not listening; start the application and retry.";
563
+ }
564
+ if (code === "UNIX_TARGET_REFUSED") {
565
+ return "The request was not executed; check the unix socket path, owner and directory permissions.";
566
+ }
567
+ return "The request was not dispatched to the application.";
568
+ }
569
+ function projectCliUnixFailure(result) {
570
+ const found = findUnixTransportError(toolCauseFromResult(result));
571
+ if (!found)
572
+ return result;
573
+ if (found.delivery === "not-dispatched") {
574
+ return {
575
+ ok: false,
576
+ code: found.code,
577
+ details: {
578
+ message: notDispatchedMessage(found),
579
+ delivery: "not-dispatched",
580
+ ...found.socketPath !== undefined && { socketPath: found.socketPath },
581
+ ...found.causeCode !== undefined && { errno: found.causeCode }
582
+ },
583
+ hint: notDispatchedHint(found.code),
584
+ retryable: found.code === "UNIX_CONNECT_FAILED"
585
+ };
586
+ }
587
+ if (found.delivery === "possibly-dispatched") {
588
+ const code = found.code === "UNIX_HEADERS_TIMEOUT" ? "UNIX_HEADERS_TIMEOUT" : "UNIX_DELIVERY_UNCERTAIN";
589
+ const message = found.code === "UNIX_HEADERS_TIMEOUT" ? `Outcome unknown, not retried: ${found.message}` : `Outcome unknown, not retried: connection closed after the request was sent (${found.message})`;
590
+ return {
591
+ ok: false,
592
+ code,
593
+ details: {
594
+ message,
595
+ delivery: "possibly-dispatched",
596
+ ...found.socketPath !== undefined && { socketPath: found.socketPath }
597
+ },
598
+ hint: "The request may have been executed by the application before the connection closed; inspect state before retrying.",
599
+ retryable: false
600
+ };
601
+ }
602
+ return {
603
+ ok: false,
604
+ code: found.code,
605
+ details: {
606
+ message: found.message,
607
+ delivery: "response-received"
608
+ },
609
+ retryable: false
610
+ };
611
+ }
612
+ function projectCliNativeFailure(error) {
613
+ const projected = ApiError2.is(error) ? projectRemoteError(error) : error;
614
+ return projectCliUnixFailure(toolResultFromError(projected));
513
615
  }
514
616
 
515
617
  // src/tools/cli/view.ts
@@ -903,7 +1005,7 @@ async function executeCliCommand(definition, rawArgs, options, writers, coerceJs
903
1005
  }
904
1006
  return { ok: true, data: checked.data };
905
1007
  } catch (error) {
906
- return toolResultFromError(error);
1008
+ return projectCliNativeFailure(error);
907
1009
  }
908
1010
  }
909
1011
  function emitCliViewOrResult(policy, result, options, writers, emit, initialShown, mediaExitCode = 0) {
@@ -943,22 +1045,23 @@ var IN_PROCESS_RUN_OPTIONS = Object.freeze({
943
1045
  });
944
1046
  function shapeCliInvocationResult(result, toolName, config, policy) {
945
1047
  if (!result.ok) {
946
- const normalized = toolErrorFromResult(result);
1048
+ const mapped = applyToolErrorMapping(result, config.errors);
1049
+ const normalized = toolErrorFromResult(mapped);
947
1050
  const hints = [];
948
- if (result.hint)
949
- hints.push(result.hint);
950
- const global = config.errorHint?.(toolName, result.code);
1051
+ if (mapped.hint)
1052
+ hints.push(mapped.hint);
1053
+ const global = config.errorHint?.(toolName, mapped.code);
951
1054
  if (global)
952
1055
  hints.push(global);
953
1056
  return {
954
1057
  ok: false,
955
- exitCode: cliExitCode2(result, config.exitCodes),
1058
+ exitCode: cliExitCode2(mapped, config.exitCodes),
956
1059
  error: {
957
- code: result.code,
1060
+ code: mapped.code,
958
1061
  message: normalized.message,
959
- ...result.details !== undefined && { details: result.details },
1062
+ ...mapped.details !== undefined && { details: mapped.details },
960
1063
  ...hints.length > 0 && { hint: hints.join(" ") },
961
- ...result.retryable !== undefined && { retryable: result.retryable }
1064
+ ...mapped.retryable !== undefined && { retryable: mapped.retryable }
962
1065
  }
963
1066
  };
964
1067
  }
@@ -1281,113 +1384,15 @@ function assertCliPoliciesResolved(commands, config) {
1281
1384
  }
1282
1385
  }
1283
1386
 
1284
- // src/tools/cli/unix-outcome.ts
1285
- var MAX_CAUSE_DEPTH = 16;
1286
- var UNIX_ERROR_CODES = new Set(UNIX_CLIENT_TRANSPORT_ERROR_CODES);
1287
- var UNIX_DELIVERY_STATES = new Set(UNIX_CLIENT_DELIVERY_STATES);
1288
- function ownString(value, key) {
1289
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
1290
- return descriptor && "value" in descriptor && typeof descriptor.value === "string" ? descriptor.value : undefined;
1291
- }
1292
- function isUnixErrorCode(value) {
1293
- return value !== undefined && UNIX_ERROR_CODES.has(value);
1294
- }
1295
- function isUnixDeliveryState(value) {
1296
- return value !== undefined && UNIX_DELIVERY_STATES.has(value);
1297
- }
1298
- function findUnixTransportError(root) {
1299
- const visited = new Set;
1300
- let current = root;
1301
- for (let depth = 0;depth < MAX_CAUSE_DEPTH && current !== undefined; depth += 1) {
1302
- if (typeof current !== "object" || current === null || visited.has(current))
1303
- return;
1304
- visited.add(current);
1305
- if (current instanceof Error && ownString(current, "name") === UNIX_CLIENT_TRANSPORT_ERROR_NAME) {
1306
- const code = ownString(current, "code");
1307
- const delivery = ownString(current, "delivery");
1308
- if (isUnixErrorCode(code) && isUnixDeliveryState(delivery)) {
1309
- const inner = current.cause;
1310
- const causeCode = typeof inner === "object" && inner !== null ? ownString(inner, "code") : undefined;
1311
- const causePath = typeof inner === "object" && inner !== null ? ownString(inner, "path") : undefined;
1312
- const socketPath = ownString(current, "socketPath") ?? causePath;
1313
- return {
1314
- code,
1315
- delivery,
1316
- message: current.message,
1317
- ...causeCode !== undefined && { causeCode },
1318
- ...socketPath !== undefined && { socketPath }
1319
- };
1320
- }
1321
- }
1322
- current = "cause" in current ? Reflect.get(current, "cause") : undefined;
1323
- }
1324
- return;
1325
- }
1326
- function notDispatchedMessage(found) {
1327
- if (found.code === "UNIX_CONNECT_FAILED") {
1328
- const target = found.socketPath ? `"${found.socketPath}"` : "the unix socket";
1329
- const suffix = found.causeCode ? ` (${found.causeCode})` : "";
1330
- return `Not executed: application is not listening on ${target}${suffix}`;
1331
- }
1332
- if (found.code === "UNIX_TARGET_REFUSED") {
1333
- return `Not executed: unix socket target refused — ${found.message}`;
1334
- }
1335
- return `Not executed: ${found.message}`;
1336
- }
1337
- function notDispatchedHint(code) {
1338
- if (code === "UNIX_CONNECT_FAILED") {
1339
- return "The request was not executed because the application is not listening; start the application and retry.";
1340
- }
1341
- if (code === "UNIX_TARGET_REFUSED") {
1342
- return "The request was not executed; check the unix socket path, owner and directory permissions.";
1343
- }
1344
- return "The request was not dispatched to the application.";
1387
+ // src/tools/cli/runner.ts
1388
+ var cliInvokerErrors = new WeakMap;
1389
+ function registerCliInvokerErrors(invoker, errors) {
1390
+ if (errors !== undefined)
1391
+ cliInvokerErrors.set(invoker, errors);
1345
1392
  }
1346
- function projectCliUnixFailure(result) {
1347
- const found = findUnixTransportError(toolCauseFromResult(result));
1348
- if (!found)
1349
- return result;
1350
- if (found.delivery === "not-dispatched") {
1351
- return {
1352
- ok: false,
1353
- code: found.code,
1354
- details: {
1355
- message: notDispatchedMessage(found),
1356
- delivery: "not-dispatched",
1357
- ...found.socketPath !== undefined && { socketPath: found.socketPath },
1358
- ...found.causeCode !== undefined && { errno: found.causeCode }
1359
- },
1360
- hint: notDispatchedHint(found.code),
1361
- retryable: found.code === "UNIX_CONNECT_FAILED"
1362
- };
1363
- }
1364
- if (found.delivery === "possibly-dispatched") {
1365
- const code = found.code === "UNIX_HEADERS_TIMEOUT" ? "UNIX_HEADERS_TIMEOUT" : "UNIX_DELIVERY_UNCERTAIN";
1366
- const message = found.code === "UNIX_HEADERS_TIMEOUT" ? `Outcome unknown, not retried: ${found.message}` : `Outcome unknown, not retried: connection closed after the request was sent (${found.message})`;
1367
- return {
1368
- ok: false,
1369
- code,
1370
- details: {
1371
- message,
1372
- delivery: "possibly-dispatched",
1373
- ...found.socketPath !== undefined && { socketPath: found.socketPath }
1374
- },
1375
- hint: "The request may have been executed by the application before the connection closed; inspect state before retrying.",
1376
- retryable: false
1377
- };
1378
- }
1379
- return {
1380
- ok: false,
1381
- code: found.code,
1382
- details: {
1383
- message: found.message,
1384
- delivery: "response-received"
1385
- },
1386
- retryable: false
1387
- };
1393
+ function cliInvokerErrorMapping(invoker) {
1394
+ return cliInvokerErrors.get(invoker);
1388
1395
  }
1389
-
1390
- // src/tools/cli/runner.ts
1391
1396
  function assertCliAuthConfig(config) {
1392
1397
  if (config.auth !== undefined && config.resolveAuth !== undefined) {
1393
1398
  throw new Error("[stitchkit] createCli: use either auth or resolveAuth, not both");
@@ -1407,11 +1412,14 @@ function createCliToolRunner(config, lifecycle, auth, typedGlobals) {
1407
1412
  context: { ...config.context?.(auth, typedGlobals), signal: config.signal },
1408
1413
  hooks: config.hooks,
1409
1414
  lifecycle,
1410
- coerceJsonArgs: config.coerceJsonArgs
1415
+ coerceJsonArgs: config.coerceJsonArgs,
1416
+ errors: config.errors
1411
1417
  });
1412
1418
  return async (tool, rawArgs, context, call) => {
1413
1419
  const result = await run(tool, rawArgs, context, call);
1414
- return result.ok ? result : projectCliUnixFailure(result);
1420
+ if (result.ok)
1421
+ return result;
1422
+ return applyToolErrorMapping(projectCliUnixFailure(result), config.errors);
1415
1423
  };
1416
1424
  }
1417
1425
 
@@ -1437,6 +1445,7 @@ function cliInvocationResult2(result, toolName, config) {
1437
1445
  }
1438
1446
  async function createCliInvoker2(config, globals) {
1439
1447
  const lifecycle = resolveOptionalCliToolAccess("createCliInvoker", config);
1448
+ assertErrorCodeMapping("createCliInvoker", config.errors);
1440
1449
  assertNoLegacyCliPolicyKeys(config);
1441
1450
  assertCliAuthConfig(config);
1442
1451
  const typedGlobals = parseCliGlobalValues(config.globalOptions, globals);
@@ -1453,7 +1462,7 @@ async function createCliInvoker2(config, globals) {
1453
1462
  }
1454
1463
  const { tools, help } = buildCliSurface(config, auth, typedGlobals, allNativeHelp, new Set, invokerCommandShapeIssue);
1455
1464
  const runTool = isInspectOnlyLifecycle(lifecycle) ? undefined : createCliToolRunner(config, lifecycle, auth, typedGlobals);
1456
- return {
1465
+ const invoker = {
1457
1466
  commands: [
1458
1467
  ...[...natives].map(([name, definition]) => ({
1459
1468
  name,
@@ -1470,7 +1479,8 @@ async function createCliInvoker2(config, globals) {
1470
1479
  return executeNativeCommand(native, args, config.coerceJsonArgs ?? true, typedGlobals, {
1471
1480
  mode: "in-process",
1472
1481
  errorHint: config.errorHint,
1473
- exitCodes: config.exitCodes
1482
+ exitCodes: config.exitCodes,
1483
+ errors: config.errors
1474
1484
  });
1475
1485
  }
1476
1486
  const tool = tools.get(command);
@@ -1490,6 +1500,8 @@ async function createCliInvoker2(config, globals) {
1490
1500
  return shapeCliInvocationResult(result, command, config, cliResultPolicy(config, command));
1491
1501
  }
1492
1502
  };
1503
+ registerCliInvokerErrors(invoker, config.errors);
1504
+ return invoker;
1493
1505
  }
1494
1506
  function buildCliSurface(config, auth, typedGlobals, nativeHelp, applicationGlobalNames, shapeIssue) {
1495
1507
  resolveOptionalCliToolAccess("buildCliSurface", config);
@@ -1551,119 +1563,6 @@ function managedCliDescriptor(tool) {
1551
1563
  };
1552
1564
  }
1553
1565
 
1554
- // src/tools/cli/io.ts
1555
- import { writeSync } from "node:fs";
1556
-
1557
- // src/tools/cli/stdin.ts
1558
- function readPipedStdin(input = process.stdin) {
1559
- if (input.isTTY || input.readableEnded)
1560
- return Promise.resolve(null);
1561
- if (input.destroyed)
1562
- return Promise.reject(new Error("stdin closed before EOF"));
1563
- return new Promise((resolve, reject) => {
1564
- const chunks = [];
1565
- const cleanup = () => {
1566
- clearTimeout(timer);
1567
- input.pause();
1568
- input.off("data", onData);
1569
- input.off("end", onEnd);
1570
- input.off("error", onError);
1571
- input.off("close", onClose);
1572
- };
1573
- const onData = (chunk) => {
1574
- if (chunk.length === 0)
1575
- return;
1576
- clearTimeout(timer);
1577
- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
1578
- };
1579
- const onEnd = () => {
1580
- cleanup();
1581
- const text = Buffer.concat(chunks).toString("utf8").trim();
1582
- resolve(text.length > 0 ? text : null);
1583
- };
1584
- const onError = (error) => {
1585
- cleanup();
1586
- reject(error);
1587
- };
1588
- const onClose = () => onError(new Error("stdin closed before EOF"));
1589
- const timer = setTimeout(() => {
1590
- cleanup();
1591
- resolve(null);
1592
- }, 250);
1593
- input.on("end", onEnd);
1594
- input.on("error", onError);
1595
- input.on("close", onClose);
1596
- input.on("data", onData);
1597
- input.resume();
1598
- });
1599
- }
1600
-
1601
- // src/tools/cli/io.ts
1602
- function isReaderGone(error) {
1603
- const code = errnoOf(error);
1604
- return code === "EPIPE" || code === "ERR_STREAM_DESTROYED";
1605
- }
1606
- function createCliIo(config) {
1607
- let pendingWrite;
1608
- let writeFailed = false;
1609
- const writeFd = (fd, text) => {
1610
- const bytes = Buffer.from(text, "utf8");
1611
- let offset = 0;
1612
- while (offset < bytes.length) {
1613
- try {
1614
- offset += writeSync(fd, bytes, offset, bytes.length - offset);
1615
- } catch (error) {
1616
- if (fd === 1 && isReaderGone(error))
1617
- throw error;
1618
- if (errnoOf(error) === "EAGAIN") {
1619
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1);
1620
- continue;
1621
- }
1622
- const stream = fd === 1 ? process.stdout : process.stderr;
1623
- const rest = bytes.subarray(offset);
1624
- pendingWrite = new Promise((resolve) => {
1625
- stream.write(rest, (failure) => {
1626
- if (failure)
1627
- writeFailed = true;
1628
- resolve();
1629
- });
1630
- });
1631
- return;
1632
- }
1633
- }
1634
- };
1635
- const writeStdout = config.stdout ?? ((text) => writeFd(1, text));
1636
- let readerGone = false;
1637
- const stdoutWhileOpen = (text) => {
1638
- if (readerGone)
1639
- return false;
1640
- try {
1641
- writeStdout(text);
1642
- return true;
1643
- } catch (error) {
1644
- if (!isReaderGone(error))
1645
- throw error;
1646
- readerGone = true;
1647
- return false;
1648
- }
1649
- };
1650
- const stdout = (text) => {
1651
- stdoutWhileOpen(text);
1652
- };
1653
- const stderr = config.stderr ?? ((text) => writeFd(2, text));
1654
- const exit = config.exit ?? ((code) => {
1655
- if (pendingWrite === undefined)
1656
- process.exit(code);
1657
- else
1658
- pendingWrite.then(() => process.exit(writeFailed ? 1 : code));
1659
- });
1660
- const readStdin = config.stdin ?? readPipedStdin;
1661
- return { stdout, stdoutWhileOpen, stderr, exit, readStdin };
1662
- }
1663
-
1664
- // src/tools/cli/notices.ts
1665
- import { AsyncLocalStorage } from "node:async_hooks";
1666
-
1667
1566
  // src/tools/cli/args-view.ts
1668
1567
  function resolveCliView(flags, ascending) {
1669
1568
  if (flags.size === 0) {
@@ -2243,438 +2142,6 @@ function scanCliInvocation2(argv, options) {
2243
2142
  };
2244
2143
  }
2245
2144
 
2246
- // src/tools/cli/notices.ts
2247
- var invocationNotices = new AsyncLocalStorage;
2248
- function withCliNotices(quiet, stderr, run) {
2249
- return invocationNotices.run({ quiet, stderr }, run);
2250
- }
2251
- function writeCliNotice(text) {
2252
- const invocation = invocationNotices.getStore();
2253
- if (invocation !== undefined) {
2254
- if (!invocation.quiet)
2255
- invocation.stderr(text);
2256
- return;
2257
- }
2258
- const scan = scanCliInvocation2(process.argv.slice(2));
2259
- if (scan.error !== undefined || scan.framework.quiet)
2260
- return;
2261
- process.stderr.write(text);
2262
- }
2263
-
2264
- // src/tools/cli/download.ts
2265
- import { createHash } from "node:crypto";
2266
- import { basename as basename2, resolve } from "node:path";
2267
-
2268
- // src/internal/write-download.ts
2269
- import path from "node:path";
2270
- async function writeDownload(root, name, data) {
2271
- if (!isSafeEntryName(name) || path.basename(name) !== name) {
2272
- throw new Error("download name escapes the output dir");
2273
- }
2274
- const parent = { handle: root, basename: name };
2275
- const metadata = await containedEntryMetadata(parent);
2276
- await writeContainedFile({
2277
- parent,
2278
- content: data,
2279
- replace: true,
2280
- ...metadata?.isFile() && { mode: metadata.mode }
2281
- });
2282
- }
2283
-
2284
- // src/tools/cli/inline-files.ts
2285
- import { basename } from "node:path";
2286
- import { pathToFileURL } from "node:url";
2287
- import { z as z3 } from "zod";
2288
- var EmbeddedResourceSchema = z3.object({
2289
- type: z3.literal("resource"),
2290
- resource: z3.union([
2291
- z3.object({ uri: z3.string(), mimeType: z3.string().optional(), blob: z3.string() }),
2292
- z3.object({ uri: z3.string(), mimeType: z3.string().optional(), text: z3.string() })
2293
- ])
2294
- });
2295
- var InlineFileSchema = z3.discriminatedUnion("type", [
2296
- McpImageContentSchema,
2297
- McpAudioContentSchema,
2298
- EmbeddedResourceSchema
2299
- ]);
2300
- function inlineFileBlocks(data) {
2301
- if (!isRecord(data) || !Array.isArray(data.content))
2302
- return [];
2303
- return data.content.flatMap((part, index) => {
2304
- const parsed = InlineFileSchema.safeParse(part);
2305
- return parsed.success ? [{ index, file: parsed.data }] : [];
2306
- });
2307
- }
2308
- function decodeBase64(data, maxBytes) {
2309
- const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
2310
- const decodedLength = Math.floor((data.length - padding) * 3 / 4);
2311
- if (data.length > Math.ceil(maxBytes / 3) * 4 || decodedLength > maxBytes) {
2312
- throw new Error(`file exceeds the ${maxBytes}-byte cap`);
2313
- }
2314
- if (data.length % 4 === 1 || padding > 0 && data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(data)) {
2315
- throw new Error("invalid base64");
2316
- }
2317
- const bytes = Buffer.from(data, "base64");
2318
- if (!bytes.toString("base64").startsWith(data))
2319
- throw new Error("invalid base64");
2320
- return bytes;
2321
- }
2322
- function encodeText(text, maxBytes) {
2323
- const bytes = text.length > maxBytes ? undefined : Buffer.from(text, "utf8");
2324
- if (!bytes || bytes.length > maxBytes) {
2325
- throw new Error(`file exceeds the ${maxBytes}-byte cap`);
2326
- }
2327
- return bytes;
2328
- }
2329
- function inlineFileBytes(file, maxBytes) {
2330
- if (file.type !== "resource")
2331
- return decodeBase64(file.data, maxBytes);
2332
- return "blob" in file.resource ? decodeBase64(file.resource.blob, maxBytes) : encodeText(file.resource.text, maxBytes);
2333
- }
2334
- function uriFileName(uri) {
2335
- try {
2336
- return basename(new URL(uri).pathname);
2337
- } catch {
2338
- return "";
2339
- }
2340
- }
2341
- function inlineFileMimeType(file) {
2342
- return file.type === "resource" ? file.resource.mimeType : file.mimeType;
2343
- }
2344
- function ownFileName(file) {
2345
- if (file.type === "resource")
2346
- return uriFileName(file.resource.uri) || undefined;
2347
- const name = file._meta?.[MCP_FILE_NAME_META_KEY2];
2348
- return typeof name === "string" ? name : undefined;
2349
- }
2350
- function inlineFileName(file, digest) {
2351
- return ownFileName(file) ?? `${file.type}-${digest}${mediaExtension(inlineFileMimeType(file) ?? "") ?? ".bin"}`;
2352
- }
2353
- function linkSavedFiles(data, blocks, saved) {
2354
- if (!isRecord(data) || !Array.isArray(data.content))
2355
- return data;
2356
- const links = new Map;
2357
- for (const block of blocks) {
2358
- const file = saved(block);
2359
- if (!file)
2360
- continue;
2361
- const mimeType = inlineFileMimeType(block.file);
2362
- links.set(block.index, {
2363
- type: "resource_link",
2364
- uri: pathToFileURL(file.path).href,
2365
- name: file.name,
2366
- ...mimeType !== undefined && { mimeType },
2367
- size: file.size
2368
- });
2369
- }
2370
- if (links.size === 0)
2371
- return data;
2372
- return { ...data, content: data.content.map((part, index) => links.get(index) ?? part) };
2373
- }
2374
-
2375
- // src/tools/cli/download.ts
2376
- var DEFAULT_DOWNLOAD_MAX_BYTES = 100 * 1024 * 1024;
2377
- async function saveResultMedia(data, options) {
2378
- const blocks = inlineFileBlocks(data);
2379
- const sources = [...options.download?.(data) ?? [], ...blocks];
2380
- if (sources.length === 0) {
2381
- if (!options.quiet)
2382
- options.stderr(`--output-dir: the result carries no files to save
2383
- `);
2384
- return { ok: true, data };
2385
- }
2386
- const batch = await saveBatch(sources, options);
2387
- return {
2388
- ok: batch.ok,
2389
- data: linkSavedFiles(data, blocks, (block) => batch.files.get(block))
2390
- };
2391
- }
2392
- async function saveBatch(sources, { dir, allowPrivateHosts, maxBytes, timeoutMs, quiet, stderr }) {
2393
- const root = resolve(dir);
2394
- const files = new Map;
2395
- let directory;
2396
- try {
2397
- directory = await openPinnedDirectory(root, { create: true, readable: false });
2398
- } catch (error) {
2399
- stderr(`failed to prepare download directory: ${error instanceof Error ? error.message : String(error)}
2400
- `);
2401
- return { ok: false, files };
2402
- }
2403
- let ok = true;
2404
- const digests = new Map;
2405
- try {
2406
- for (const source of sources) {
2407
- try {
2408
- const bytes = "url" in source ? await fetchDownload(source.url, allowPrivateHosts, maxBytes, timeoutMs) : inlineFileBytes(source.file, maxBytes);
2409
- const digest = createHash("sha256").update(bytes).digest("hex");
2410
- const name = basename2("url" in source ? source.name : inlineFileName(source.file, digest));
2411
- const path = resolve(root, name);
2412
- const written = digests.get(name);
2413
- if (written === undefined) {
2414
- await writeDownload(directory, name, bytes);
2415
- digests.set(name, digest);
2416
- if (!quiet)
2417
- stderr(`saved ${path} (${(bytes.length / 1024).toFixed(0)}KB)
2418
- `);
2419
- } else if (written !== digest) {
2420
- throw new Error(`another file of this batch is already saved as ${JSON.stringify(name)}`);
2421
- }
2422
- files.set(source, { path, name, size: bytes.length });
2423
- } catch (err) {
2424
- ok = false;
2425
- const reason = errnoOf(err) ?? (err instanceof Error ? err.message : String(err));
2426
- const subject = "url" in source ? `failed to download ${source.url}` : `failed to save content[${source.index}]`;
2427
- stderr(`${subject}: ${reason}
2428
- `);
2429
- }
2430
- }
2431
- } finally {
2432
- try {
2433
- await directory.close();
2434
- } catch (error) {
2435
- ok = false;
2436
- stderr(`failed to close download directory: ${error instanceof Error ? error.message : String(error)}
2437
- `);
2438
- }
2439
- }
2440
- return { ok, files };
2441
- }
2442
- async function fetchDownload(url, allowPrivateHosts, maxBytes, timeoutMs) {
2443
- const res = await fetchGuarded(new URL(url), allowPrivateHosts, { timeoutMs });
2444
- if (!res.ok)
2445
- throw new Error(`HTTP ${res.status}`);
2446
- const bytes = await readCapped(res, maxBytes);
2447
- if (!bytes)
2448
- throw new Error(`file exceeds the ${maxBytes}-byte cap`);
2449
- return bytes;
2450
- }
2451
-
2452
- // src/tools/cli/help.ts
2453
- var GLOBAL_OPTIONS = [
2454
- ["--json", "Emit compact success/error JSON records (for scripts)"],
2455
- ["--wait", "Block-poll an async result to a terminal state"],
2456
- ["--wait-timeout <s>", "Override the --wait timeout in seconds"],
2457
- ["--output-dir <dir>", "Save the files a result names or carries into a directory"],
2458
- ["--quiet", "Suppress non-essential stderr output"],
2459
- ["--dry-run", "Print the resolved call without executing it"],
2460
- ["--schema", "Print the JSON Schema of a command input and output"],
2461
- ["--help, -h", "Show help for a command"],
2462
- ["--help <text>", "List only the commands matching a substring"],
2463
- ["--count-by <field>", "Count records per distinct value of a field"],
2464
- ["--sum <field>", "Total a numeric field, optionally grouped by --by"],
2465
- ["--sort <field>", "Order the records by a field, largest first"],
2466
- ["--ascending", "Flip --sort to smallest first"],
2467
- ["--top <n>", "Keep the n leading entries of the view asked for"],
2468
- ["--table <a,b>", "Render the named fields as an aligned table"]
2469
- ];
2470
- function typeLabel(schema) {
2471
- if (HELP_SHOWN_KEYWORDS.has("enum") && Array.isArray(schema.enum)) {
2472
- return schema.enum.join("|");
2473
- }
2474
- if (HELP_SHOWN_KEYWORDS.has("type")) {
2475
- if (schema.type === "array")
2476
- return "value";
2477
- if (typeof schema.type === "string")
2478
- return schema.type;
2479
- }
2480
- return "value";
2481
- }
2482
- function isPatternOnly(member) {
2483
- return isRecord(member) && typeof member.pattern === "string" && Object.keys(member).every((key) => key === "pattern" || key === "type");
2484
- }
2485
- function constraintLabel(schema) {
2486
- const limits = [];
2487
- const format = HELP_SHOWN_KEYWORDS.has("format") && typeof schema.format === "string" ? schema.format : undefined;
2488
- const pattern = HELP_SHOWN_KEYWORDS.has("pattern") && typeof schema.pattern === "string" ? schema.pattern : undefined;
2489
- const named = format !== undefined && STANDARD_STRING_FORMATS.has(format);
2490
- if (format !== undefined && (named || pattern === undefined)) {
2491
- limits.push(format);
2492
- } else if (pattern !== undefined) {
2493
- limits.push(`pattern /${pattern}/`);
2494
- }
2495
- const bounds = [
2496
- ["minimum", ">="],
2497
- ["exclusiveMinimum", ">"],
2498
- ["maximum", "<="],
2499
- ["exclusiveMaximum", "<"],
2500
- ["minLength", "length >="],
2501
- ["maxLength", "length <="],
2502
- ["minItems", "items >="],
2503
- ["maxItems", "items <="]
2504
- ];
2505
- for (const [keyword, label] of bounds) {
2506
- if (!HELP_SHOWN_KEYWORDS.has(keyword))
2507
- continue;
2508
- const bound = schema[keyword];
2509
- if (typeof bound !== "number")
2510
- continue;
2511
- if (schema.type === "integer" && Math.abs(bound) === Number.MAX_SAFE_INTEGER)
2512
- continue;
2513
- limits.push(`${label}${bound}`);
2514
- }
2515
- const compositions = [
2516
- ["anyOf", "any of", " | "],
2517
- ["oneOf", "one of", " | "],
2518
- ["allOf", "all of", " & "]
2519
- ];
2520
- for (const [keyword, label, separator] of compositions) {
2521
- if (!HELP_SHOWN_KEYWORDS.has(keyword))
2522
- continue;
2523
- const members = schema[keyword];
2524
- if (!Array.isArray(members))
2525
- continue;
2526
- const stated = named && keyword === "allOf" ? members.filter((member) => !isPatternOnly(member)) : members;
2527
- const branches = stated.map((member) => {
2528
- const constraints = isRecord(member) ? constraintLabel(member) : "";
2529
- const type = isRecord(member) ? typeLabel(member) : member === false ? "no value" : "any value";
2530
- return { constraints, text: `${type}${constraints}` };
2531
- });
2532
- if (branches.every((branch) => branch.constraints === ""))
2533
- continue;
2534
- limits.push(`${label}: ${branches.map((branch) => branch.text).join(separator)}`);
2535
- }
2536
- return limits.length === 0 ? "" : ` [${limits.join(", ")}]`;
2537
- }
2538
- function fieldTypeLabel(schema) {
2539
- return `<${typeLabel(schema)}>${constraintLabel(schema)}`;
2540
- }
2541
- function nullableField(schema) {
2542
- if (schema.type === "null")
2543
- return true;
2544
- if (Array.isArray(schema.type) && schema.type.includes("null"))
2545
- return true;
2546
- return Array.isArray(schema.anyOf) && schema.anyOf.some((member) => isRecord(member) && nullableField(member));
2547
- }
2548
- function jsonValueHelp(fields) {
2549
- const example = fields.find((field) => nullableField(field.schema))?.name;
2550
- return [
2551
- "Assign a whole JSON value with --field:=JSON; the declared schema still validates it.",
2552
- ...example === undefined ? [] : [`JSON null: --${example}:=null. The literal string stays --${example} null.`]
2553
- ];
2554
- }
2555
- function padRight(text, width) {
2556
- return text.length >= width ? text : text + " ".repeat(width - text.length);
2557
- }
2558
- function summarize(desc) {
2559
- const firstLine = desc.split(`
2560
- `)[0]?.trim() ?? "";
2561
- const firstSentence = firstLine.split(". ")[0]?.trim() ?? firstLine;
2562
- const max = 72;
2563
- return firstSentence.length > max ? `${firstSentence.slice(0, max - 1).trimEnd()}…` : firstSentence;
2564
- }
2565
- function applicationOptionLines(fields) {
2566
- if (fields.length === 0)
2567
- return [];
2568
- const labels = new Map(fields.map((field) => [field.name, `--${field.name} ${fieldTypeLabel(field.schema)}`]));
2569
- const width = Math.max(...fields.map((field) => labels.get(field.name)?.length ?? 0));
2570
- return [
2571
- "",
2572
- "Application options:",
2573
- ...fields.map((field) => ` ${padRight(labels.get(field.name) ?? `--${field.name}`, width)} ${field.description ?? ""}`.trimEnd())
2574
- ];
2575
- }
2576
- function filterCommands(commands, filter) {
2577
- const needle = filter.toLowerCase();
2578
- return new Map([...commands].filter(([command, descriptor]) => command.toLowerCase().includes(needle) || descriptor.description.toLowerCase().includes(needle)));
2579
- }
2580
- function renderTopHelp(input) {
2581
- const { name, version, defaultCommand } = input;
2582
- const commands = input.filter === undefined ? input.commands : filterCommands(input.commands, input.filter);
2583
- const lines = [
2584
- `${name} ${version}`,
2585
- "",
2586
- `Usage: ${name} ${defaultCommand ? "[command]" : "<command>"} [args] [--flags]`,
2587
- "",
2588
- input.filter === undefined ? "Commands:" : `Commands matching "${input.filter}" (${commands.size} of ${input.commands.size}):`
2589
- ];
2590
- const width = Math.max(0, ...[...commands.keys()].map((key) => key.length));
2591
- for (const [command, descriptor] of commands) {
2592
- lines.push(` ${padRight(command, width)} ${summarize(descriptor.description)}${command === defaultCommand ? " (default)" : ""}${descriptor.unavailableReason !== undefined ? " [unavailable]" : ""}`);
2593
- if (descriptor.unavailableReason !== undefined) {
2594
- lines.push(` Unavailable: ${descriptor.unavailableReason}`);
2595
- }
2596
- }
2597
- if (input.unavailable !== undefined) {
2598
- lines.push("", `Managed commands are unavailable: ${input.unavailable}`);
2599
- }
2600
- if (input.filter !== undefined) {
2601
- lines.push("", `Run "${name} <command> --help" for command-specific flags.`);
2602
- return `${lines.join(`
2603
- `)}
2604
- `;
2605
- }
2606
- lines.push("", "Global options:");
2607
- const optWidth = Math.max(...GLOBAL_OPTIONS.map(([flag]) => flag.length));
2608
- for (const [flag, desc] of GLOBAL_OPTIONS)
2609
- lines.push(` ${padRight(flag, optWidth)} ${desc}`);
2610
- lines.push(...applicationOptionLines(input.applicationOptions));
2611
- lines.push("", ...jsonValueHelp(input.applicationOptions));
2612
- lines.push("", `Run "${name} <command> --help" for command-specific flags.`);
2613
- return `${lines.join(`
2614
- `)}
2615
- `;
2616
- }
2617
- function renderCommandHelp(name, command, descriptor, applicationOptions = []) {
2618
- const fields = jsonSchemaFields(descriptor.presentationSchema);
2619
- const fieldsByName = new Map(fields.map((field) => [field.name, field]));
2620
- const kinds = describeSchemaFields(descriptor.argumentSchema);
2621
- const positionals = [];
2622
- const positionalNames = descriptor.positionals ?? [...kinds].filter(([, info]) => info.kind !== "boolean").map(([fieldName]) => fieldName);
2623
- for (const fieldName of positionalNames) {
2624
- const field = fieldsByName.get(fieldName);
2625
- if (field)
2626
- positionals.push(field);
2627
- }
2628
- const variadicTail = descriptor.positionals !== undefined && kinds.get(descriptor.positionals[descriptor.positionals.length - 1] ?? "")?.kind === "array" ? descriptor.positionals[descriptor.positionals.length - 1] : undefined;
2629
- const positionalSyntax = new Map(positionals.map((field) => {
2630
- const label = field.name === variadicTail ? `${field.name}...` : field.name;
2631
- return [field.name, field.required ? `<${label}>` : `[${label}]`];
2632
- }));
2633
- const usage = [
2634
- `Usage: ${name} ${command}`,
2635
- ...positionals.map((field) => positionalSyntax.get(field.name) ?? field.name),
2636
- "[--flags]"
2637
- ].join(" ");
2638
- const lines = [descriptor.description, "", usage, ""];
2639
- if (descriptor.unavailableReason !== undefined) {
2640
- lines.push(`Unavailable: ${descriptor.unavailableReason}`, "");
2641
- }
2642
- if (fields.length > 0) {
2643
- lines.push("Arguments:");
2644
- const labels = new Map(fields.map((field) => {
2645
- const positional = positionalSyntax.get(field.name);
2646
- const alias = descriptor.aliases.get(field.name);
2647
- const option = alias ? `-${alias}, --${field.name}` : `--${field.name}`;
2648
- return [field.name, positional ? `${positional} | ${option}` : option];
2649
- }));
2650
- const width = Math.max(...fields.map((field) => labels.get(field.name)?.length ?? 0));
2651
- for (const f of fields) {
2652
- const req = f.required ? " (required)" : "";
2653
- const desc = f.description ? ` — ${f.description}` : "";
2654
- const label = labels.get(f.name) ?? `--${f.name}`;
2655
- lines.push(` ${padRight(label, width)} ${fieldTypeLabel(f.schema)}${req}${desc}`);
2656
- }
2657
- const flag = [...kinds].find(([, info]) => info.kind === "boolean")?.[0];
2658
- if (flag !== undefined) {
2659
- lines.push("", `A boolean flag is on alone or takes true/false: --${flag}, --${flag} false, --no-${flag}`);
2660
- }
2661
- const arrays = [...kinds].filter(([, info]) => info.kind === "array");
2662
- for (const [field] of arrays) {
2663
- lines.push("", `Repeat --${field} <value> for each element, or assign the whole array with --${field}:=JSON.`);
2664
- }
2665
- if (arrays.length > 0 && descriptor.positionals === undefined) {
2666
- lines.push("Array options cannot be combined with automatic positional arguments; name other fields with flags.");
2667
- }
2668
- lines.push("", ...jsonValueHelp(fields), "");
2669
- }
2670
- const applicationLines = applicationOptionLines(applicationOptions);
2671
- if (applicationLines.length > 0)
2672
- lines.push(...applicationLines.slice(1), "");
2673
- return `${lines.join(`
2674
- `)}
2675
- `;
2676
- }
2677
-
2678
2145
  // src/tools/cli/managed-surface.ts
2679
2146
  async function buildManagedSurface(session, typedGlobals, forExecution) {
2680
2147
  const { config, nativeHelp, applicationGlobalNames } = session;
@@ -2684,7 +2151,7 @@ async function buildManagedSurface(session, typedGlobals, forExecution) {
2684
2151
  try {
2685
2152
  auth = await resolveIdentity();
2686
2153
  } catch (error) {
2687
- const failure = toolResultFromError(error);
2154
+ const failure = applyToolErrorMapping(projectCliNativeFailure(error), config.errors);
2688
2155
  const normalized = toolErrorFromResult(failure);
2689
2156
  return {
2690
2157
  resolved: false,
@@ -2698,367 +2165,10 @@ async function buildManagedSurface(session, typedGlobals, forExecution) {
2698
2165
  return { resolved: true, auth, help, tools, streams };
2699
2166
  }
2700
2167
 
2701
- // src/tools/cli/args-tokens.ts
2702
- function readCliTokens(argv, fields, fieldFor, config) {
2703
- const fwState = {
2704
- fw: { json: false, wait: false, quiet: false, dryRun: false, help: false, schema: false },
2705
- fwFlags: new Map,
2706
- viewFlags: new Map,
2707
- ascending: false
2708
- };
2709
- const flags = new Map;
2710
- const jsonFields = new Set;
2711
- const literalBooleanFlags = new Set;
2712
- const positionals = [];
2713
- const pushFlag = (name, value, json = false) => {
2714
- appendCliFieldValue(flags, jsonFields, name, value, fieldFor(name), json);
2715
- };
2716
- const adjacent = (index) => !config.separatedBefore?.has(index);
2717
- let optionsEnded = false;
2718
- for (let i = 0;i < argv.length; i++) {
2719
- const tok = argv[i];
2720
- if (tok === undefined)
2721
- continue;
2722
- if (!optionsEnded && tok === "--") {
2723
- optionsEnded = true;
2724
- continue;
2725
- }
2726
- if (optionsEnded || !looksLikeOption(tok)) {
2727
- positionals.push(tok);
2728
- continue;
2729
- }
2730
- if (tok === "-h") {
2731
- fwState.fw.help = true;
2732
- continue;
2733
- }
2734
- if (!tok.startsWith("--")) {
2735
- const match = /^-([A-Za-z])(?:=(.*))?$/.exec(tok);
2736
- const alias = match?.[1];
2737
- const field = alias === undefined ? undefined : config.aliases?.get(alias);
2738
- if (!alias || !field)
2739
- throw new CliArgumentError2(`Unknown option "${tok}"`);
2740
- const inline = match?.[2];
2741
- const info = fieldFor(field);
2742
- if (info?.kind === "boolean") {
2743
- const separate = inline === undefined && adjacent(i + 1) ? separateBoolValue(argv[i + 1]) : undefined;
2744
- if (separate !== undefined)
2745
- i++;
2746
- pushFlag(field, inline ?? String(separate ?? true));
2747
- if (inline !== undefined && info.pureBoolean === true) {
2748
- parseReservedBool(field, inline);
2749
- }
2750
- literalBooleanFlags.add(field);
2751
- continue;
2752
- }
2753
- let value = inline;
2754
- if (value === undefined) {
2755
- const next = adjacent(i + 1) ? argv[i + 1] : undefined;
2756
- if (next !== undefined && !isOptionToken(next)) {
2757
- value = next;
2758
- i++;
2759
- } else {
2760
- throw new CliArgumentError2(`--${field} requires a value`);
2761
- }
2762
- }
2763
- pushFlag(field, value);
2764
- continue;
2765
- }
2766
- const option = classifyLongOptionToken(tok);
2767
- if (!option)
2768
- throw new CliArgumentError2(`Unknown option "${tok}"`);
2769
- const { name, json } = cliFieldOption(option, fields);
2770
- let { value } = option;
2771
- if (name.length === 0)
2772
- throw new CliArgumentError2("Invalid empty option name");
2773
- if (json && RESERVED_CLI_OPTIONS.has(name)) {
2774
- throw new CliArgumentError2(`--${name} is a framework option and does not accept :=JSON`);
2775
- }
2776
- if (option.globalKind !== undefined) {
2777
- i = consumeFrameworkOptionToken(argv, i, option, fwState, {
2778
- adjacent,
2779
- onError: (error) => {
2780
- throw error;
2781
- }
2782
- });
2783
- continue;
2784
- }
2785
- if (value === undefined && name.startsWith("no-") && !fieldFor(name) && fieldFor(name.slice(3))?.kind === "boolean") {
2786
- pushFlag(name.slice(3), "false");
2787
- literalBooleanFlags.add(name.slice(3));
2788
- continue;
2789
- }
2790
- const unsafeSegment = name.split(".").find(isUnsafeKey);
2791
- if (unsafeSegment !== undefined) {
2792
- throw new CliArgumentError2(`Unsafe option name "--${name}"`);
2793
- }
2794
- const info = fieldFor(name);
2795
- const rootName = name.split(".")[0] ?? name;
2796
- if (!fields.has(rootName) && !config.allowUnknown) {
2797
- throw new CliArgumentError2(`Unknown option "--${name}"`);
2798
- }
2799
- if (value === undefined) {
2800
- if (info?.kind === "boolean") {
2801
- const separate = adjacent(i + 1) ? separateBoolValue(argv[i + 1]) : undefined;
2802
- if (separate !== undefined)
2803
- i++;
2804
- pushFlag(name, String(separate ?? true));
2805
- literalBooleanFlags.add(name);
2806
- continue;
2807
- }
2808
- const next = adjacent(i + 1) ? argv[i + 1] : undefined;
2809
- if (next !== undefined && !isOptionToken(next)) {
2810
- value = next;
2811
- i++;
2812
- } else {
2813
- throw new CliArgumentError2(`--${name} requires a value`);
2814
- }
2815
- }
2816
- pushFlag(name, value, json);
2817
- if (option.inline && !json && info?.kind === "boolean" && info.pureBoolean === true) {
2818
- parseReservedBool(name, value);
2819
- }
2820
- }
2821
- const { fw } = fwState;
2822
- const options = {
2823
- json: fw.json,
2824
- wait: fw.wait,
2825
- quiet: fw.quiet,
2826
- dryRun: fw.dryRun,
2827
- help: fw.help,
2828
- schema: fw.schema,
2829
- ...fw.waitTimeout !== undefined && { waitTimeout: fw.waitTimeout },
2830
- ...fw.outputDir !== undefined && { outputDir: fw.outputDir }
2831
- };
2832
- return {
2833
- options,
2834
- flags,
2835
- jsonFields,
2836
- literalBooleanFlags,
2837
- viewFlags: fwState.viewFlags,
2838
- ascending: fwState.ascending,
2839
- positionals
2840
- };
2841
- }
2842
-
2843
- // src/tools/cli/args.ts
2844
- function buildToolArgs(tokens, fields, fieldFor, declaredPositionals, allowUnknown) {
2845
- const { flags, jsonFields, literalBooleanFlags, positionals } = tokens;
2846
- if (declaredPositionals === undefined && positionals.length > 0) {
2847
- const arrayFlag = [...flags.keys()].find((key) => fieldFor(key)?.kind === "array");
2848
- if (arrayFlag !== undefined) {
2849
- throw new CliArgumentError2(`--${arrayFlag} cannot be combined with automatic positional arguments. Repeat --${arrayFlag} for each element or use --${arrayFlag}:=JSON; name other fields with flags, or declare a positional policy.`);
2850
- }
2851
- }
2852
- const toolArgs = {};
2853
- const fillable = declaredPositionals === undefined ? [...fields.entries()].filter(([, info]) => info.kind !== "boolean").map(([name]) => name) : [...declaredPositionals];
2854
- const variadicTail = declaredPositionals !== undefined && fields.get(fillable[fillable.length - 1] ?? "")?.kind === "array" ? fillable[fillable.length - 1] : undefined;
2855
- let pi = 0;
2856
- for (const key of fillable) {
2857
- if (pi >= positionals.length)
2858
- break;
2859
- if (key === variadicTail) {
2860
- if (flags.has(key)) {
2861
- throw new CliArgumentError2(`--${key} conflicts with the positional values for "${key}" — pass one form, not both`);
2862
- }
2863
- toolArgs[key] = coerceField(fields.get(key), positionals.slice(pi), `<${key}>`);
2864
- pi = positionals.length;
2865
- break;
2866
- }
2867
- if (flags.has(key))
2868
- continue;
2869
- const value = positionals[pi++];
2870
- if (value !== undefined) {
2871
- toolArgs[key] = coerceField(fields.get(key), [value], `<${key}>`);
2872
- }
2873
- }
2874
- if (pi < positionals.length) {
2875
- throw new CliArgumentError2(`Unexpected positional argument "${positionals[pi]}"`);
2876
- }
2877
- const dottedRoots = new Map;
2878
- for (const key of flags.keys()) {
2879
- const dot = key.indexOf(".");
2880
- const exactLiteralBoolean = literalBooleanFlags.has(key) && fields.has(key);
2881
- if (dot > 0 && !exactLiteralBoolean) {
2882
- dottedRoots.set(key.slice(0, dot), key);
2883
- }
2884
- }
2885
- for (const [root, dotted] of dottedRoots) {
2886
- if (flags.has(root)) {
2887
- throw new CliArgumentError2(`--${root} conflicts with --${dotted} — pass one form, not both`);
2888
- }
2889
- }
2890
- for (const key of jsonFields) {
2891
- for (const other of flags.keys()) {
2892
- if (other.startsWith(`${key}.`) || key.startsWith(`${other}.`)) {
2893
- throw new CliArgumentError2(`--${key} conflicts with --${other} — pass one form, not both`);
2894
- }
2895
- }
2896
- }
2897
- for (const [key, values] of flags) {
2898
- const info = fieldFor(key);
2899
- const exactLiteralBoolean = literalBooleanFlags.has(key) && fields.has(key);
2900
- if (key.includes(".") && !exactLiteralBoolean) {
2901
- const root = key.split(".")[0] ?? key;
2902
- const value = !jsonFields.has(key) && info === undefined && allowUnknown && !fields.has(root) ? looseCoerce(values[0] ?? "") : coerceCliFieldValue(info, values, `--${key}`, jsonFields.has(key));
2903
- setNested(toolArgs, key.split("."), value);
2904
- continue;
2905
- }
2906
- toolArgs[key] = coerceCliFieldValue(info, values, `--${key}`, jsonFields.has(key));
2907
- }
2908
- return toolArgs;
2909
- }
2910
- function cliRunOptions(framework) {
2911
- return {
2912
- json: framework.json,
2913
- wait: framework.wait,
2914
- quiet: framework.quiet,
2915
- dryRun: framework.dryRun,
2916
- help: framework.help,
2917
- schema: framework.schema,
2918
- ...framework.waitTimeout !== undefined && { waitTimeout: framework.waitTimeout },
2919
- ...framework.outputDir !== undefined && { outputDir: framework.outputDir },
2920
- ...framework.view !== undefined && { view: framework.view }
2921
- };
2922
- }
2923
- function parseCliArgs2(argv, schema, config = {}) {
2924
- try {
2925
- return parseCommandArgv(argv, schema, config);
2926
- } catch (error) {
2927
- if (!(error instanceof CliArgumentError2))
2928
- throw error;
2929
- const scan = scanCliArgv(argv, {
2930
- afterCommand: true,
2931
- separatedBefore: config.separatedBefore
2932
- });
2933
- if (!answersBeforeArguments(scan))
2934
- throw error;
2935
- return { toolArgs: {}, options: cliRunOptions(scan.framework) };
2936
- }
2937
- }
2938
- function parseCommandArgv(argv, schema, config) {
2939
- const fields = describeSchemaFields(schema);
2940
- for (const name of config.knownFields ?? []) {
2941
- if (!fields.has(name))
2942
- fields.set(name, { kind: "other" });
2943
- }
2944
- const fieldFor = (name) => fields.get(name) ?? (name.includes(".") ? describeSchemaPath(schema, name.split(".")) : undefined);
2945
- const tokens = readCliTokens(argv, fields, fieldFor, config);
2946
- const { options } = tokens;
2947
- const view = resolveCliView(tokens.viewFlags, tokens.ascending);
2948
- if (view)
2949
- options.view = view;
2950
- return {
2951
- toolArgs: buildToolArgs(tokens, fields, fieldFor, config.positionals, config.allowUnknown === true),
2952
- options
2953
- };
2954
- }
2955
- function extractCliGlobalOptions2(argv, schema) {
2956
- if (schema === undefined)
2957
- return { argv: [...argv], globals: {} };
2958
- let result;
2959
- try {
2960
- result = scanCliArgv(argv, { appGlobals: schema });
2961
- } catch (error) {
2962
- if (error instanceof CliArgumentError2) {
2963
- return { argv: [], globals: {}, error };
2964
- }
2965
- throw error;
2966
- }
2967
- const early = answersBeforeArguments(result);
2968
- const error = early ? undefined : result.appGlobalError ?? result.liftedBoundaryError;
2969
- if (error !== undefined) {
2970
- return {
2971
- argv: [],
2972
- globals: result.globals,
2973
- error
2974
- };
2975
- }
2976
- return {
2977
- argv: result.withoutGlobals,
2978
- globals: result.globals,
2979
- ...result.separatedBeforeGlobals.size > 0 && {
2980
- separatedBefore: result.separatedBeforeGlobals
2981
- }
2982
- };
2983
- }
2984
-
2985
- // src/tools/cli/prepare.ts
2986
- function looseCoerceValue(value) {
2987
- if (Array.isArray(value))
2988
- return value.map(looseCoerceValue);
2989
- return typeof value === "string" ? looseCoerce(value) : value;
2990
- }
2991
- function passthroughBase(value) {
2992
- if (isRecord(value))
2993
- return value;
2994
- if (typeof value === "string") {
2995
- try {
2996
- const parsed = safeJsonParse(value);
2997
- if (isRecord(parsed))
2998
- return parsed;
2999
- } catch {}
3000
- }
3001
- return;
3002
- }
3003
- function collectPassthrough(toolArgs, field, knownKeys) {
3004
- const known = new Set(knownKeys);
3005
- const bag = {};
3006
- for (const key of Object.keys(toolArgs)) {
3007
- if (key === field || known.has(key))
3008
- continue;
3009
- bag[key] = looseCoerceValue(toolArgs[key]);
3010
- delete toolArgs[key];
3011
- }
3012
- if (Object.keys(bag).length === 0)
3013
- return;
3014
- const base = passthroughBase(toolArgs[field]);
3015
- toolArgs[field] = base ? { ...base, ...bag } : bag;
3016
- }
3017
- async function prepareInvocation(command, commandTokens, separatedBefore, framework, descriptor, config, readStdin) {
3018
- const passthroughField = cliPassthroughField(config, command);
3019
- let parsed;
3020
- try {
3021
- parsed = parseCliArgs2(commandTokens, descriptor.argumentSchema, {
3022
- allowUnknown: passthroughField !== undefined,
3023
- knownFields: jsonSchemaFields(descriptor.presentationSchema).map((field) => field.name),
3024
- aliases: new Map([...descriptor.aliases].map(([field, alias]) => [alias, field])),
3025
- positionals: descriptor.positionals,
3026
- separatedBefore
3027
- });
3028
- } catch (error) {
3029
- if (!(error instanceof CliArgumentError2))
3030
- throw error;
3031
- return { ok: false, message: error.message };
3032
- }
3033
- const { toolArgs } = parsed;
3034
- const options = cliRunOptions(framework);
3035
- const firstUnset = jsonSchemaFields(descriptor.presentationSchema).find((field) => field.required && !(field.name in toolArgs) && field.schema.type !== "boolean");
3036
- if (firstUnset) {
3037
- const piped = await readStdin();
3038
- if (piped !== null) {
3039
- if (descriptor.positionals === undefined) {
3040
- toolArgs[firstUnset.name] = piped;
3041
- } else {
3042
- const fieldInfo = describeSchemaFields(descriptor.argumentSchema).get(firstUnset.name);
3043
- try {
3044
- toolArgs[firstUnset.name] = coerceField(fieldInfo, [piped], `--${firstUnset.name}`);
3045
- } catch (error) {
3046
- if (!(error instanceof CliArgumentError2))
3047
- throw error;
3048
- return { ok: false, message: error.message };
3049
- }
3050
- }
3051
- }
3052
- }
3053
- if (passthroughField) {
3054
- collectPassthrough(toolArgs, passthroughField, objectShapeKeys(descriptor.argumentSchema));
3055
- }
3056
- return { ok: true, toolArgs, options };
3057
- }
3058
-
3059
2168
  // src/tools/cli/session.ts
3060
2169
  function createCliSession(config, io) {
3061
2170
  const lifecycle = resolveOptionalCliToolAccess("createCliSession", config);
2171
+ assertErrorCodeMapping("createCliSession", config.errors);
3062
2172
  assertNoLegacyCliPolicyKeys(config);
3063
2173
  assertCliAuthConfig(config);
3064
2174
  assertPositiveSafeInteger("createCli maxDownloadBytes", config.maxDownloadBytes);
@@ -3150,398 +2260,9 @@ function emitOptionsFor(config, json, toolName) {
3150
2260
  json,
3151
2261
  toolName,
3152
2262
  errorHint: config.errorHint,
3153
- exitCodes: { ...DEFAULT_EXIT_CODES2, ...config.exitCodes }
3154
- };
3155
- }
3156
-
3157
- // src/tools/cli/run-stream.ts
3158
- async function runStreamCommand(session, route, managed, stream, { toolArgs, options }) {
3159
- const { config } = session;
3160
- const { stdout, stderr, exit } = session.io;
3161
- const command = stream.tool.name;
3162
- if (options.wait || options.outputDir !== undefined || options.view !== undefined) {
3163
- stderr(`--wait, --output-dir and aggregate views do not apply to stream command "${command}"
3164
- `);
3165
- return exit(2);
3166
- }
3167
- const abort = new AbortController;
3168
- let cancelled = false;
3169
- const cancel = () => {
3170
- cancelled = true;
3171
- abort.abort(config.signal?.reason);
3172
- };
3173
- if (config.signal?.aborted)
3174
- cancel();
3175
- else
3176
- config.signal?.addEventListener("abort", cancel, { once: true });
3177
- const runTool = createCliToolRunner(config, session.lifecycle, managed.auth, route.typedGlobals);
3178
- let opened;
3179
- try {
3180
- opened = await runTool(stream.tool, toolArgs, { signal: abort.signal });
3181
- } catch (error) {
3182
- opened = toolResultFromError(error);
3183
- }
3184
- const policy = cliResultPolicy(config, command);
3185
- let outcome;
3186
- if (!opened.ok)
3187
- outcome = opened;
3188
- else if (!isAsyncIterable(opened.data)) {
3189
- outcome = toolResultFromError(new Error(`Stream command "${command}" handler did not return an async iterable`));
3190
- } else {
3191
- outcome = await printStreamItems(opened.data, stream, abort, () => cancelled, (item) => session.io.stdoutWhileOpen(streamLine(command, item, policy, options)));
3192
- }
3193
- config.signal?.removeEventListener("abort", cancel);
3194
- if (outcome === "completed" || outcome === "reader-gone")
3195
- return exit(0);
3196
- if (outcome === "cancelled" || cancelled) {
3197
- return exit(cliExitCode2({ ok: false, code: "REQUEST_ABORTED" }, config.exitCodes));
3198
- }
3199
- return exit(emitResult2(outcome, { stdout, stderr }, emitOptionsFor(config, options.json, command)));
3200
- }
3201
- function streamLine(command, item, policy, options) {
3202
- if (policy?.present === undefined)
3203
- return `${stringifyJsonSafe(item)}
3204
- `;
3205
- let line;
3206
- try {
3207
- line = policy.present({ result: item, options });
3208
- if (typeof line !== "string")
3209
- throw new Error("CLI result presenter must return a string");
3210
- } catch (error) {
3211
- throw new AppError2("CLI_PRESENTATION_FAILED", {
3212
- message: "A stream item was produced, but its presentation failed.",
3213
- status: 500,
3214
- details: { command, cause: formatToolError(toolResultFromError(error)) }
3215
- });
3216
- }
3217
- return line;
3218
- }
3219
- async function printStreamItems(source, { descriptor }, abort, wasCancelled, write) {
3220
- const iterator = source[Symbol.asyncIterator]();
3221
- let lifetimeExpired = false;
3222
- const lifetime = descriptor.lifetimeMs === undefined ? undefined : setTimeout(() => {
3223
- lifetimeExpired = true;
3224
- abort.abort(new Error("Stream lifetime expired"));
3225
- }, descriptor.lifetimeMs);
3226
- lifetime?.unref?.();
3227
- try {
3228
- for await (const { item } of readContractStreamItems(iterator, descriptor, abort.signal)) {
3229
- if (!write(item))
3230
- return "reader-gone";
3231
- }
3232
- return "completed";
3233
- } catch (error) {
3234
- if (wasCancelled())
3235
- return "cancelled";
3236
- if (lifetimeExpired) {
3237
- return toolResultFromError(contractStreamLifetimeExceeded());
3238
- }
3239
- return projectCliUnixFailure(toolResultFromError(error));
3240
- } finally {
3241
- if (lifetime !== undefined)
3242
- clearTimeout(lifetime);
3243
- abort.abort();
3244
- Promise.resolve().then(() => iterator.return?.(undefined)).catch(() => {
3245
- return;
3246
- });
3247
- }
3248
- }
3249
-
3250
- // src/tools/cli/wait.ts
3251
- var DEFAULT_TIMEOUT = 600;
3252
- function waitFailure(tool, result) {
3253
- return {
3254
- ok: false,
3255
- code: "WAIT_FAILED",
3256
- details: {
3257
- message: `"${tool}" reached a terminal failed state`,
3258
- result
3259
- }
2263
+ exitCodes: config.exitCodes,
2264
+ errors: config.errors
3260
2265
  };
3261
2266
  }
3262
- async function pollUntilDone2(params) {
3263
- const { initial, wait, call } = params;
3264
- if (!initial.ok)
3265
- return initial;
3266
- if (wait.failed?.(initial.data))
3267
- return waitFailure(wait.tool, initial.data);
3268
- if (wait.done(initial.data))
3269
- return initial;
3270
- const pollArgs = wait.poll(initial.data);
3271
- if (!pollArgs)
3272
- return initial;
3273
- const timeoutSec = params.timeoutSec ?? wait.timeout ?? DEFAULT_TIMEOUT;
3274
- let failedState;
3275
- const { state, timedOut } = await pollUntil({
3276
- poll: () => call(wait.tool, pollArgs),
3277
- done: (result) => {
3278
- if (!result.ok)
3279
- return true;
3280
- if (wait.failed?.(result.data)) {
3281
- failedState = result;
3282
- return true;
3283
- }
3284
- return wait.done(result.data);
3285
- },
3286
- backoff: wait.backoff,
3287
- timeoutSec,
3288
- sleepFn: params.sleepFn,
3289
- onTick: params.onTick,
3290
- signal: params.signal
3291
- });
3292
- if (timedOut) {
3293
- return {
3294
- ok: false,
3295
- code: "TIMEOUT",
3296
- details: { message: `Timed out after ${timeoutSec}s waiting for "${wait.tool}"` }
3297
- };
3298
- }
3299
- if (state === failedState && state.ok)
3300
- return waitFailure(wait.tool, state.data);
3301
- return state;
3302
- }
3303
-
3304
- // src/tools/cli/run-managed.ts
3305
- async function runManagedInvocation(session, route) {
3306
- const { config } = session;
3307
- const { stdout, stderr, exit } = session.io;
3308
- const { command, topLevelHelp, helpRequested, schemaRequested } = route;
3309
- const managed = await buildManagedSurface(session, route.typedGlobals, !topLevelHelp && !helpRequested && !schemaRequested && !isInspectOnlyLifecycle(session.lifecycle));
3310
- if (topLevelHelp || command === undefined)
3311
- return respondTopLevelHelp(session, route, managed);
3312
- if (!managed.resolved) {
3313
- return exit(emitResult2(managed.failure, { stdout, stderr }, emitOptionsFor(config, route.framework.json, command)));
3314
- }
3315
- return runManagedCommand(session, route, command, managed);
3316
- }
3317
- function respondTopLevelHelp(session, route, managed) {
3318
- const { config, applicationOptions } = session;
3319
- const { stdout, stderr, exit } = session.io;
3320
- const filter = route.helpFilter;
3321
- if (filter !== undefined && filterCommands(managed.help, filter).size === 0) {
3322
- stderr(`no command matches "${filter}" (${[...managed.help.values()].filter((entry) => entry.unavailableReason === undefined).length} available)
3323
- ` + (managed.resolved ? "" : `Managed commands are unavailable: ${managed.reason}
3324
- `));
3325
- const codes = { ...DEFAULT_EXIT_CODES2, ...config.exitCodes };
3326
- exit(codes.NOT_FOUND ?? 4);
3327
- return;
3328
- }
3329
- stdout(renderTopHelp({
3330
- name: config.name,
3331
- version: config.version,
3332
- commands: managed.help,
3333
- defaultCommand: config.defaultCommand,
3334
- applicationOptions,
3335
- ...filter !== undefined && { filter },
3336
- ...managed.resolved ? {} : { unavailable: managed.reason }
3337
- }));
3338
- exit(0);
3339
- }
3340
- async function runManagedCommand(session, route, command, managed) {
3341
- const { config, applicationOptions } = session;
3342
- const { stdout, stderr, exit, readStdin } = session.io;
3343
- const descriptor = managed.help.get(command);
3344
- if (!descriptor) {
3345
- stderr(`Unknown command "${command}". Run "${config.name} --help" for the command list.
3346
- `);
3347
- return exit(cliExitCode2(unknownCliCommand(command), config.exitCodes));
3348
- }
3349
- if (route.helpRequested) {
3350
- stdout(renderCommandHelp(config.name, command, descriptor, applicationOptions));
3351
- return exit(0);
3352
- }
3353
- if (route.schemaRequested) {
3354
- stdout(renderCommandSchema(command, descriptor));
3355
- return exit(0);
3356
- }
3357
- const inspectErr = inspectOnlyError(session.lifecycle);
3358
- if (inspectErr) {
3359
- return exit(emitResult2(toolResultFromError(inspectErr), { stdout, stderr }, emitOptionsFor(config, route.framework.json, command)));
3360
- }
3361
- if (descriptor.unavailableReason !== undefined) {
3362
- return exit(emitResult2(unavailableCommand(descriptor.unavailableReason), { stdout, stderr }, emitOptionsFor(config, route.framework.json, command)));
3363
- }
3364
- const stream = managed.streams.get(command);
3365
- const tool = managed.tools.get(command);
3366
- if (!tool && !stream)
3367
- throw new Error("[stitchkit] managed CLI executable invariant failed");
3368
- const prepared = await prepareInvocation(command, route.commandTokens, route.separatedBefore, route.framework, descriptor, config, readStdin);
3369
- if (!prepared.ok) {
3370
- stderr(`${prepared.message}
3371
- `);
3372
- return exit(2);
3373
- }
3374
- const { toolArgs, options } = prepared;
3375
- if (options.wait && !cliWaitConfig(config, command)) {
3376
- stderr(`--wait is not configured for command "${command}"
3377
- `);
3378
- return exit(2);
3379
- }
3380
- if (options.waitTimeout !== undefined && !options.wait) {
3381
- stderr(`--wait-timeout requires --wait
3382
- `);
3383
- return exit(2);
3384
- }
3385
- if (options.dryRun) {
3386
- stdout(`${JSON.stringify({ command, args: toolArgs }, null, 2)}
3387
- `);
3388
- return exit(0);
3389
- }
3390
- if (stream)
3391
- return runStreamCommand(session, route, managed, stream, { toolArgs, options });
3392
- if (!tool)
3393
- throw new Error("[stitchkit] managed CLI executable invariant failed");
3394
- if (options.view !== undefined && !options.wait) {
3395
- try {
3396
- assertViewColumns(options.view, descriptor.outputSchema);
3397
- } catch (error) {
3398
- if (!(error instanceof CliArgumentError2))
3399
- throw error;
3400
- stderr(`${error.message}
3401
- `);
3402
- return exit(2);
3403
- }
3404
- }
3405
- const result = await executeManagedTool(session, route, command, managed, tool, {
3406
- toolArgs,
3407
- options
3408
- });
3409
- return emitManagedResult(session, command, result, options, isRepeatableRead(tool.method));
3410
- }
3411
- async function executeManagedTool(session, route, command, managed, tool, { toolArgs, options }) {
3412
- const { config } = session;
3413
- const { stderr } = session.io;
3414
- const runTool = createCliToolRunner(config, session.lifecycle, managed.auth, route.typedGlobals);
3415
- let result;
3416
- try {
3417
- result = await runTool(tool, toolArgs);
3418
- } catch (err) {
3419
- result = toolResultFromError(err);
3420
- }
3421
- const waitConfig = cliWaitConfig(config, command);
3422
- if (options.wait && waitConfig) {
3423
- result = await pollUntilDone2({
3424
- initial: result,
3425
- wait: waitConfig,
3426
- call: async (toolName, args) => {
3427
- const unavailable = managed.help.get(toolName)?.unavailableReason;
3428
- if (unavailable !== undefined)
3429
- return unavailableCommand(unavailable);
3430
- const pollTool = managed.tools.get(toolName);
3431
- if (!pollTool) {
3432
- return {
3433
- ok: false,
3434
- code: "UNKNOWN_OPERATION",
3435
- details: {
3436
- message: `--wait: no command "${toolName}" to poll`,
3437
- operation: toolName
3438
- }
3439
- };
3440
- }
3441
- return runTool(pollTool, args);
3442
- },
3443
- timeoutSec: options.waitTimeout,
3444
- onTick: options.quiet ? undefined : (attempt) => stderr(`waiting… (poll ${attempt})
3445
- `),
3446
- signal: config.signal
3447
- });
3448
- }
3449
- return result;
3450
- }
3451
- async function emitManagedResult(session, command, result, options, repeatable) {
3452
- const { config } = session;
3453
- const { stdout, stderr, exit } = session.io;
3454
- const emit = { ...emitOptionsFor(config, options.json, command), repeatable };
3455
- if (!result.ok)
3456
- return exit(emitResult2(result, { stdout, stderr }, emit));
3457
- let shown = result;
3458
- let mediaExitCode = 0;
3459
- if (options.outputDir !== undefined) {
3460
- const saved = await saveResultMedia(result.data, {
3461
- dir: options.outputDir,
3462
- download: config.download,
3463
- allowPrivateHosts: config.allowPrivateDownloadHosts ?? false,
3464
- maxBytes: config.maxDownloadBytes ?? DEFAULT_DOWNLOAD_MAX_BYTES,
3465
- timeoutMs: config.downloadTimeoutMs,
3466
- quiet: options.quiet,
3467
- stderr
3468
- });
3469
- shown = { ...result, data: saved.data };
3470
- if (!saved.ok)
3471
- mediaExitCode = 1;
3472
- }
3473
- return exit(emitCliViewOrResult(cliResultPolicy(config, command), result, options, { stdout, stderr }, emit, shown, mediaExitCode));
3474
- }
3475
-
3476
- // src/tools/cli/run-native.ts
3477
- async function runNativeCommand(session, route, command, native) {
3478
- const { config, applicationOptions, nativeHelp } = session;
3479
- const { stdout, stderr, exit, readStdin } = session.io;
3480
- const { commandTokens, separatedBefore, framework, helpRequested, globals } = route;
3481
- const descriptor = nativeHelp.get(command);
3482
- if (!descriptor)
3483
- throw new Error("[stitchkit] native CLI descriptor invariant failed");
3484
- if (helpRequested) {
3485
- stdout(renderCommandHelp(config.name, command, descriptor, applicationOptions));
3486
- return exit(0);
3487
- }
3488
- if (route.schemaRequested) {
3489
- stdout(renderCommandSchema(command, descriptor));
3490
- return exit(0);
3491
- }
3492
- const prepared = await prepareInvocation(command, commandTokens, separatedBefore, framework, descriptor, config, readStdin);
3493
- if (!prepared.ok) {
3494
- stderr(`${prepared.message}
3495
- `);
3496
- return exit(2);
3497
- }
3498
- const { toolArgs, options } = prepared;
3499
- if (options.wait) {
3500
- stderr(`--wait is not configured for native command "${command}"
3501
- `);
3502
- return exit(2);
3503
- }
3504
- if (options.waitTimeout !== undefined) {
3505
- stderr(`--wait-timeout requires --wait
3506
- `);
3507
- return exit(2);
3508
- }
3509
- if (options.outputDir !== undefined) {
3510
- stderr(`--output-dir is not configured for native commands
3511
- `);
3512
- return exit(2);
3513
- }
3514
- if (options.dryRun) {
3515
- stdout(`${JSON.stringify({ command, args: toolArgs }, null, 2)}
3516
- `);
3517
- return exit(0);
3518
- }
3519
- return exit(await executeNativeCommand(native, toolArgs, config.coerceJsonArgs ?? true, globals, {
3520
- mode: "terminal",
3521
- options,
3522
- writers: { stdout, stderr },
3523
- emit: { ...emitOptionsFor(config, options.json, command), repeatable: false }
3524
- }));
3525
- }
3526
-
3527
- // src/tools/cli/create-cli.ts
3528
- async function createCli2(config) {
3529
- resolveOptionalCliToolAccess("createCli", config);
3530
- assertNoLegacyCliPolicyKeys(config);
3531
- const io = createCliIo(config);
3532
- const argv = config.argv ?? process.argv.slice(2);
3533
- const session = createCliSession(config, io);
3534
- const route = resolveCliRoute(session, argv);
3535
- if (route === undefined)
3536
- return;
3537
- return withCliNotices(route.quiet, io.stderr, () => {
3538
- const { command } = route;
3539
- const native = command === undefined ? undefined : session.nativeCommands.get(command);
3540
- if (native && command !== undefined) {
3541
- return runNativeCommand(session, route, command, native);
3542
- }
3543
- return runManagedInvocation(session, route);
3544
- });
3545
- }
3546
2267
 
3547
- export { CliArgumentError2, DEFAULT_EXIT_CODES2, cliExitCode2, emitResult2, renderCliView2, defineCliResult2, defineCliCommand2, cliInvocationResult2, createCliInvoker2, scanCliArgv, answersBeforeArguments, scanCliInvocation2, writeCliNotice, parseCliArgs2, extractCliGlobalOptions2, pollUntilDone2, createCli2 };
2268
+ export { CliArgumentError2, describeSchemaFields, describeSchemaPath, separateBoolValue, parseReservedBool, looseCoerce, coerceField, setNested, DEFAULT_EXIT_CODES2, cliExitCode2, emitResult2, projectCliUnixFailure, renderCliView2, assertViewColumns, defineCliResult2, defineCliCommand2, emitCliViewOrResult, executeNativeCommand, cliFieldOption, appendCliFieldValue, coerceCliFieldValue, isOptionToken, looksLikeOption, RESERVED_CLI_OPTIONS, classifyLongOptionToken, collectCliStreams, assertNoLegacyCliPolicyKeys, cliResultPolicy, cliPassthroughField, cliWaitConfig, cliInvokerErrorMapping, createCliToolRunner, unavailableCommand, unknownCliCommand, cliInvocationResult2, createCliInvoker2, resolveCliView, consumeFrameworkOptionToken, scanCliArgv, answersBeforeArguments, scanCliInvocation2, buildManagedSurface, createCliSession, resolveCliRoute, renderCommandSchema, emitOptionsFor };