stitchkit 0.136.8 → 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 (342) hide show
  1. package/CHANGELOG.md +53 -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.js +8 -8
  66. package/dist/entrypoints/cli.d.ts +2 -0
  67. package/dist/entrypoints/cli.d.ts.map +1 -1
  68. package/dist/entrypoints/cli.js +518 -59
  69. package/dist/entrypoints/contract.d.ts +5 -1
  70. package/dist/entrypoints/contract.d.ts.map +1 -1
  71. package/dist/entrypoints/contract.js +25 -7
  72. package/dist/entrypoints/device-relay.js +20 -10
  73. package/dist/entrypoints/files/packaging.js +2 -2
  74. package/dist/entrypoints/files.js +10 -10
  75. package/dist/entrypoints/handler.d.ts +1 -1
  76. package/dist/entrypoints/handler.d.ts.map +1 -1
  77. package/dist/entrypoints/handler.js +12 -12
  78. package/dist/entrypoints/http.js +13 -12
  79. package/dist/entrypoints/index.js +36 -18
  80. package/dist/entrypoints/live.d.ts +2 -1
  81. package/dist/entrypoints/live.d.ts.map +1 -1
  82. package/dist/entrypoints/live.js +630 -1
  83. package/dist/entrypoints/node.d.ts +5 -0
  84. package/dist/entrypoints/node.d.ts.map +1 -1
  85. package/dist/entrypoints/node.js +36 -16
  86. package/dist/entrypoints/observability.js +25 -10
  87. package/dist/entrypoints/postgres.d.ts +1 -0
  88. package/dist/entrypoints/postgres.d.ts.map +1 -1
  89. package/dist/entrypoints/postgres.js +66 -0
  90. package/dist/entrypoints/primitives.js +11 -4
  91. package/dist/entrypoints/process.js +7 -7
  92. package/dist/entrypoints/react.js +1 -1
  93. package/dist/entrypoints/realtime.js +3 -3
  94. package/dist/entrypoints/remote.js +6 -29
  95. package/dist/entrypoints/server.d.ts +6 -1
  96. package/dist/entrypoints/server.d.ts.map +1 -1
  97. package/dist/entrypoints/server.js +93 -32
  98. package/dist/entrypoints/service-host/macos.js +6 -6
  99. package/dist/entrypoints/service-host/work.js +6 -6
  100. package/dist/entrypoints/service-host.js +10 -10
  101. package/dist/entrypoints/spend.js +2 -1
  102. package/dist/entrypoints/sync.js +5 -5
  103. package/dist/entrypoints/telegram.js +8 -8
  104. package/dist/entrypoints/testing.d.ts +1 -0
  105. package/dist/entrypoints/testing.d.ts.map +1 -1
  106. package/dist/entrypoints/testing.js +1501 -13
  107. package/dist/entrypoints/tools/agent.js +6 -7
  108. package/dist/entrypoints/tools/connections.js +9 -11
  109. package/dist/entrypoints/tools/contract.js +1 -2
  110. package/dist/entrypoints/tools/invoker.js +4 -5
  111. package/dist/entrypoints/tools/mcp.js +10 -11
  112. package/dist/entrypoints/tools/toolkit.d.ts +1 -1
  113. package/dist/entrypoints/tools/toolkit.d.ts.map +1 -1
  114. package/dist/entrypoints/tools/toolkit.js +29 -24
  115. package/dist/entrypoints/tools.js +28 -30
  116. package/dist/entrypoints/tracking/contract.js +2 -1
  117. package/dist/entrypoints/xlsx.js +5 -8
  118. package/dist/{index-033tyx59.js → index-0zw0hcyg.js} +4 -1
  119. package/dist/{index-zcq3dby3.js → index-1bjwfnnj.js} +1 -1
  120. package/dist/{index-3zt0r4y0.js → index-1cfacbe2.js} +4 -4
  121. package/dist/{index-gj4wdts6.js → index-1ckh9qx1.js} +1 -1
  122. package/dist/index-1pvwmbxp.js +1435 -0
  123. package/dist/{index-0s75mjh7.js → index-2e4hdh32.js} +1 -1
  124. package/dist/{index-3shdhzt6.js → index-2j0pqxkn.js} +12 -6
  125. package/dist/index-3k8w02se.js +28 -0
  126. package/dist/{index-7fjbdga8.js → index-3pb4ccj2.js} +8 -0
  127. package/dist/{index-w7e402wx.js → index-48kb4gqq.js} +46 -7
  128. package/dist/{index-cv9b7fz2.js → index-6rws2xf5.js} +8 -0
  129. package/dist/{index-bbpygynk.js → index-77w5vx0g.js} +1 -1
  130. package/dist/index-7dz1ngaf.js +35 -0
  131. package/dist/{index-y68gavb5.js → index-7n4atsm4.js} +1 -1
  132. package/dist/index-8ef1bfea.js +71 -0
  133. package/dist/{index-0x4mnwg5.js → index-8k3y9nd4.js} +6 -9
  134. package/dist/{index-ezwsqyad.js → index-8rkdkefj.js} +40 -23
  135. package/dist/{index-3cwq5byx.js → index-9nax7tkn.js} +2 -2
  136. package/dist/{index-dz6tstcp.js → index-9r6emjwz.js} +1 -1
  137. package/dist/{index-32ew02z1.js → index-c4b7d6ej.js} +5 -5
  138. package/dist/index-ceshyndf.js +284 -0
  139. package/dist/{index-w161azza.js → index-d13rw31w.js} +6 -6
  140. package/dist/{index-1h0dtfz3.js → index-dmm7vs3f.js} +1 -1
  141. package/dist/{index-ypm85xwe.js → index-dp8j2e77.js} +1 -1
  142. package/dist/{index-qqd979f7.js → index-edycjvrv.js} +9 -9
  143. package/dist/{index-18qdpbcq.js → index-egpf9dv0.js} +200 -1479
  144. package/dist/{index-fatke81t.js → index-ezgvsj9w.js} +2 -2
  145. package/dist/{index-chapre0y.js → index-f3e7tj1g.js} +1 -1
  146. package/dist/{index-df5xr2f9.js → index-frsd2a94.js} +16 -1
  147. package/dist/index-fy9mmek1.js +95 -0
  148. package/dist/{index-2331y2tf.js → index-g0gvfzrx.js} +12 -12
  149. package/dist/index-gpe8d1ka.js +19 -0
  150. package/dist/{index-4p2zx593.js → index-gyw4qd0m.js} +1 -1
  151. package/dist/index-gzqy81tw.js +172 -0
  152. package/dist/{index-yrhw10ef.js → index-h34c510q.js} +8 -4
  153. package/dist/{index-rr94xcj6.js → index-h527p1yj.js} +10 -4
  154. package/dist/{index-qj0sq69b.js → index-hgf1tbgz.js} +76 -16
  155. package/dist/{index-smvmnz5y.js → index-hvpan32x.js} +1 -1
  156. package/dist/{index-4gbybjg6.js → index-hxawqrb6.js} +2 -2
  157. package/dist/{index-0k1ba0ss.js → index-j91jffhv.js} +1 -1
  158. package/dist/{index-d01akj5n.js → index-jr4kwetx.js} +8 -8
  159. package/dist/{index-xqppqn97.js → index-ka6z48zc.js} +315 -69
  160. package/dist/{index-by8w2461.js → index-kw0segzt.js} +104 -3
  161. package/dist/{index-6f4fjygr.js → index-m5t4dr7h.js} +29 -7
  162. package/dist/{index-afaq0nc4.js → index-n0egp1ke.js} +1 -1
  163. package/dist/{index-9fzjgg86.js → index-n74rb1dq.js} +2 -2
  164. package/dist/{index-dwq6a6sq.js → index-pt25vmhc.js} +33 -16
  165. package/dist/{index-vwg0n3e6.js → index-pyazb8q4.js} +23 -14
  166. package/dist/{index-5md04mwc.js → index-qpjjbkc5.js} +4 -4
  167. package/dist/{index-08a3qfr8.js → index-r1qt6zgj.js} +1 -1
  168. package/dist/{index-ctaxjpa4.js → index-r709pqed.js} +1 -1
  169. package/dist/{index-2zrx0nzv.js → index-rzc40z6e.js} +3 -5
  170. package/dist/{index-gq35s3bm.js → index-s5axtd56.js} +2 -2
  171. package/dist/{index-edpkm3k7.js → index-scpcps66.js} +669 -16
  172. package/dist/{index-ry8m2mhg.js → index-sf2mt6wj.js} +1 -1
  173. package/dist/{index-tjhhsnjv.js → index-t1213r0t.js} +1 -1
  174. package/dist/{index-gvgtmt7a.js → index-t7efje30.js} +2 -2
  175. package/dist/{index-w3s79kcb.js → index-tzyk36dy.js} +1 -1
  176. package/dist/{index-8tn10tp6.js → index-v64bvwjr.js} +1 -1
  177. package/dist/{index-1fhbe4e4.js → index-vksbsqpb.js} +1 -1
  178. package/dist/{index-dxft2mnm.js → index-wdg7bswj.js} +1 -1
  179. package/dist/{index-ppy23bd2.js → index-wjx1zs2r.js} +7 -578
  180. package/dist/{index-efbzm2se.js → index-x2r0ma9t.js} +1 -1
  181. package/dist/{index-kd48gk7d.js → index-x8py72a3.js} +1 -1
  182. package/dist/index-xvydbxmk.js +1404 -0
  183. package/dist/index-xwaphv0d.js +31 -0
  184. package/dist/{index-a09r9ff0.js → index-y44j39yk.js} +1 -1
  185. package/dist/{index-7mjsb7zv.js → index-ybrrxjhb.js} +1 -1
  186. package/dist/{index-xsrma0jd.js → index-ysthxsa8.js} +6 -6
  187. package/dist/{index-6p5pshcd.js → index-yyh3ey4b.js} +1 -1
  188. package/dist/{index-mr3njw67.js → index-z6hq9j8j.js} +1 -1
  189. package/dist/{index-67mzzkdv.js → index-z72agxdn.js} +2 -2
  190. package/dist/{index-e4w0sfm1.js → index-z78mtc16.js} +1 -1
  191. package/dist/{index-7csn6pva.js → index-ze94h4ph.js} +5 -0
  192. package/dist/internal/json-stringify.d.ts +12 -0
  193. package/dist/internal/json-stringify.d.ts.map +1 -1
  194. package/dist/internal/unix-client-error.d.ts +4 -0
  195. package/dist/internal/unix-client-error.d.ts.map +1 -1
  196. package/dist/live/watch-contract.d.ts +4 -0
  197. package/dist/live/watch-contract.d.ts.map +1 -1
  198. package/dist/live/watch-fanout-frame.d.ts +81 -0
  199. package/dist/live/watch-fanout-frame.d.ts.map +1 -0
  200. package/dist/live/watch-fanout.d.ts +57 -0
  201. package/dist/live/watch-fanout.d.ts.map +1 -0
  202. package/dist/observability/audit.d.ts.map +1 -1
  203. package/dist/observability/spool-core.d.ts +1 -0
  204. package/dist/observability/spool-core.d.ts.map +1 -1
  205. package/dist/observability/spool-drain.d.ts +48 -0
  206. package/dist/observability/spool-drain.d.ts.map +1 -0
  207. package/dist/observability/spool.d.ts +12 -6
  208. package/dist/observability/spool.d.ts.map +1 -1
  209. package/dist/postgres/rollback-transaction.d.ts +61 -0
  210. package/dist/postgres/rollback-transaction.d.ts.map +1 -0
  211. package/dist/primitives/deadline.d.ts +4 -4
  212. package/dist/primitives/deadline.d.ts.map +1 -1
  213. package/dist/server/error-hook.d.ts +3 -32
  214. package/dist/server/error-hook.d.ts.map +1 -1
  215. package/dist/server/local-consent-key.d.ts +104 -0
  216. package/dist/server/local-consent-key.d.ts.map +1 -0
  217. package/dist/server/local-control-journal.d.ts +51 -0
  218. package/dist/server/local-control-journal.d.ts.map +1 -0
  219. package/dist/server/local-control-reporter.d.ts +32 -0
  220. package/dist/server/local-control-reporter.d.ts.map +1 -0
  221. package/dist/server/local-control.d.ts +48 -0
  222. package/dist/server/local-control.d.ts.map +1 -0
  223. package/dist/server/local-host-clients.d.ts +105 -0
  224. package/dist/server/local-host-clients.d.ts.map +1 -0
  225. package/dist/server/middleware/trust-fence.d.ts +20 -0
  226. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  227. package/dist/spend/receipt-spool.d.ts +9 -4
  228. package/dist/spend/receipt-spool.d.ts.map +1 -1
  229. package/dist/testing/tool-surface-checks.d.ts +89 -0
  230. package/dist/testing/tool-surface-checks.d.ts.map +1 -0
  231. package/dist/testing/tool-surface-cli-callable.d.ts +63 -0
  232. package/dist/testing/tool-surface-cli-callable.d.ts.map +1 -0
  233. package/dist/testing/tool-surface-dead-refs.d.ts +32 -0
  234. package/dist/testing/tool-surface-dead-refs.d.ts.map +1 -0
  235. package/dist/testing/tool-surface-gates.d.ts +72 -0
  236. package/dist/testing/tool-surface-gates.d.ts.map +1 -0
  237. package/dist/testing/tool-surface-parity-drivers.d.ts +56 -0
  238. package/dist/testing/tool-surface-parity-drivers.d.ts.map +1 -0
  239. package/dist/testing/tool-surface-parity.d.ts +28 -0
  240. package/dist/testing/tool-surface-parity.d.ts.map +1 -0
  241. package/dist/testing/tool-surface-ratchet.d.ts +71 -0
  242. package/dist/testing/tool-surface-ratchet.d.ts.map +1 -0
  243. package/dist/tools/agent-tools.d.ts +3 -0
  244. package/dist/tools/agent-tools.d.ts.map +1 -1
  245. package/dist/tools/cli/command.d.ts +3 -0
  246. package/dist/tools/cli/command.d.ts.map +1 -1
  247. package/dist/tools/cli/create-cli.d.ts.map +1 -1
  248. package/dist/tools/cli/format.d.ts +3 -6
  249. package/dist/tools/cli/format.d.ts.map +1 -1
  250. package/dist/tools/cli/invoke.d.ts +4 -0
  251. package/dist/tools/cli/invoke.d.ts.map +1 -1
  252. package/dist/tools/cli/local-key-command.d.ts +53 -0
  253. package/dist/tools/cli/local-key-command.d.ts.map +1 -0
  254. package/dist/tools/cli/managed-surface.d.ts.map +1 -1
  255. package/dist/tools/cli/run-managed.d.ts.map +1 -1
  256. package/dist/tools/cli/run-stream.d.ts.map +1 -1
  257. package/dist/tools/cli/runner.d.ts +8 -3
  258. package/dist/tools/cli/runner.d.ts.map +1 -1
  259. package/dist/tools/cli/secret.d.ts +55 -0
  260. package/dist/tools/cli/secret.d.ts.map +1 -0
  261. package/dist/tools/cli/session.d.ts +2 -2
  262. package/dist/tools/cli/session.d.ts.map +1 -1
  263. package/dist/tools/cli/stream.d.ts.map +1 -1
  264. package/dist/tools/cli/unix-outcome.d.ts +6 -0
  265. package/dist/tools/cli/unix-outcome.d.ts.map +1 -1
  266. package/dist/tools/execute-result.d.ts +20 -0
  267. package/dist/tools/execute-result.d.ts.map +1 -1
  268. package/dist/tools/execute.d.ts +3 -0
  269. package/dist/tools/execute.d.ts.map +1 -1
  270. package/dist/tools/internal/json-projection.d.ts +13 -9
  271. package/dist/tools/internal/json-projection.d.ts.map +1 -1
  272. package/dist/tools/internal/remote-error.d.ts +15 -0
  273. package/dist/tools/internal/remote-error.d.ts.map +1 -0
  274. package/dist/tools/internal/surface-projector.d.ts +2 -0
  275. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  276. package/dist/tools/invoker.d.ts +3 -0
  277. package/dist/tools/invoker.d.ts.map +1 -1
  278. package/dist/tools/mcp/handler.d.ts.map +1 -1
  279. package/dist/tools/mcp/lazy-discovery.d.ts +2 -0
  280. package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -1
  281. package/dist/tools/mcp/mount.d.ts +5 -0
  282. package/dist/tools/mcp/mount.d.ts.map +1 -1
  283. package/dist/tools/mcp/register.d.ts +2 -0
  284. package/dist/tools/mcp/register.d.ts.map +1 -1
  285. package/dist/tools/mcp/runtime-tools.d.ts +2 -0
  286. package/dist/tools/mcp/runtime-tools.d.ts.map +1 -1
  287. package/dist/tools/mcp/stdio.d.ts.map +1 -1
  288. package/dist/tools/mount.d.ts +3 -0
  289. package/dist/tools/mount.d.ts.map +1 -1
  290. package/dist/tools/read-operation.d.ts +2 -6
  291. package/dist/tools/read-operation.d.ts.map +1 -1
  292. package/dist/tools/remote.d.ts.map +1 -1
  293. package/dist/tools/runtime-tool.d.ts.map +1 -1
  294. package/dist/tools/toolkit.d.ts +10 -3
  295. package/dist/tools/toolkit.d.ts.map +1 -1
  296. package/dist/xlsx/schema.d.ts.map +1 -1
  297. package/llms/cli.2.txt +10 -8
  298. package/llms/cli.3.txt +2 -0
  299. package/llms/cli.txt +18 -3
  300. package/llms/contract.txt +47 -5
  301. package/llms/handler.txt +1 -1
  302. package/llms/live.txt +82 -0
  303. package/llms/node.txt +5 -0
  304. package/llms/observability.2.txt +1 -1
  305. package/llms/observability.txt +6 -0
  306. package/llms/postgres.txt +1 -0
  307. package/llms/server.2.txt +206 -240
  308. package/llms/server.3.txt +242 -202
  309. package/llms/server.4.txt +202 -1025
  310. package/llms/server.5.txt +1053 -255
  311. package/llms/server.6.txt +274 -0
  312. package/llms/server.txt +32 -116
  313. package/llms/spend.txt +8 -7
  314. package/llms/stitchkit.2.txt +13 -35
  315. package/llms/stitchkit.3.txt +27 -0
  316. package/llms/stitchkit.txt +81 -81
  317. package/llms/testing.txt +40 -0
  318. package/llms/tools-toolkit.txt +2 -2
  319. package/llms/tools.2.txt +29 -20
  320. package/llms/{upgrading-0.128.0-0.129.0.txt → upgrading-0.128.0-0.131.0.txt} +101 -3
  321. package/llms/{upgrading-0.130.0-0.136.0.txt → upgrading-0.132.0-0.137.0.txt} +62 -101
  322. package/llms/upgrading.txt +2 -2
  323. package/llms-full.txt +590 -171
  324. package/llms.txt +13 -13
  325. package/package.json +1 -1
  326. package/dist/index-9118dw8d.js +0 -603
  327. package/dist/index-9vj869rx.js +0 -19
  328. package/dist/index-a1rjr381.js +0 -114
  329. package/dist/index-dacxr7nf.js +0 -17
  330. package/dist/index-dm50x3by.js +0 -63
  331. package/dist/index-dmrx8xma.js +0 -163
  332. package/dist/index-ednf2cxs.js +0 -37
  333. package/dist/{index-e4zt2x70.js → index-3czppvrr.js} +3 -3
  334. package/dist/{index-42n9jycn.js → index-3f79t32b.js} +3 -3
  335. package/dist/{index-mfe9a266.js → index-84n49vam.js} +0 -0
  336. package/dist/{index-f16b7rze.js → index-er1tp8de.js} +3 -3
  337. package/dist/{index-k137ezb6.js → index-f5d0fdcf.js} +3 -3
  338. package/dist/{index-65p8v81y.js → index-psz8qrz0.js} +3 -3
  339. package/dist/{index-kadgaw1s.js → index-r8cq86h1.js} +0 -0
  340. package/dist/{index-1yky29qg.js → index-tyyvbarf.js} +0 -0
  341. package/dist/{index-tjakdpf2.js → index-wq71v08n.js} +3 -3
  342. package/dist/{index-7an2fs5h.js → index-wswcpbm4.js} +3 -3
@@ -0,0 +1,1404 @@
1
+ import {
2
+ STANDARD_STRING_FORMATS
3
+ } from "./index-ha1tv70k.js";
4
+ import {
5
+ jsonSchemaFields
6
+ } from "./index-d1pdv8qc.js";
7
+ import {
8
+ isInspectOnlyLifecycle,
9
+ inspectOnlyError,
10
+ resolveOptionalCliToolAccess,
11
+ toolResultFromError,
12
+ applyToolErrorMapping,
13
+ formatToolError
14
+ } from "./index-scpcps66.js";
15
+ import {
16
+ objectShapeKeys
17
+ } from "./index-hgf1tbgz.js";
18
+ import {
19
+ CliArgumentError2,
20
+ describeSchemaFields,
21
+ describeSchemaPath,
22
+ separateBoolValue,
23
+ parseReservedBool,
24
+ looseCoerce,
25
+ coerceField,
26
+ setNested,
27
+ cliExitCode2,
28
+ emitResult2,
29
+ projectCliUnixFailure,
30
+ assertViewColumns,
31
+ emitCliViewOrResult,
32
+ executeNativeCommand,
33
+ cliFieldOption,
34
+ appendCliFieldValue,
35
+ coerceCliFieldValue,
36
+ isOptionToken,
37
+ looksLikeOption,
38
+ RESERVED_CLI_OPTIONS,
39
+ classifyLongOptionToken,
40
+ assertNoLegacyCliPolicyKeys,
41
+ cliResultPolicy,
42
+ cliPassthroughField,
43
+ cliWaitConfig,
44
+ createCliToolRunner,
45
+ unavailableCommand,
46
+ unknownCliCommand,
47
+ resolveCliView,
48
+ consumeFrameworkOptionToken,
49
+ scanCliArgv,
50
+ answersBeforeArguments,
51
+ scanCliInvocation2,
52
+ buildManagedSurface,
53
+ createCliSession,
54
+ resolveCliRoute,
55
+ renderCommandSchema,
56
+ emitOptionsFor
57
+ } from "./index-egpf9dv0.js";
58
+ import {
59
+ isRepeatableRead
60
+ } from "./index-8k3y9nd4.js";
61
+ import {
62
+ MCP_FILE_NAME_META_KEY2,
63
+ McpImageContentSchema,
64
+ McpAudioContentSchema
65
+ } from "./index-gy9x38a2.js";
66
+ import {
67
+ readContractStreamItems,
68
+ contractStreamLifetimeExceeded
69
+ } from "./index-h34c510q.js";
70
+ import {
71
+ writeContainedFile
72
+ } from "./index-rjs94dny.js";
73
+ import {
74
+ openPinnedDirectory,
75
+ isSafeEntryName,
76
+ containedEntryMetadata
77
+ } from "./index-xrgn784x.js";
78
+ import {
79
+ pollUntil,
80
+ mediaExtension
81
+ } from "./index-mh3jdb25.js";
82
+ import {
83
+ fetchGuarded,
84
+ readCapped
85
+ } from "./index-9r6emjwz.js";
86
+ import {
87
+ stringifyJsonSafe
88
+ } from "./index-gzqy81tw.js";
89
+ import {
90
+ assertErrorCodeMapping
91
+ } from "./index-fy9mmek1.js";
92
+ import {
93
+ HELP_SHOWN_KEYWORDS
94
+ } from "./index-e413q2cj.js";
95
+ import {
96
+ isUnsafeKey,
97
+ safeJsonParse
98
+ } from "./index-zsarb5xp.js";
99
+ import {
100
+ errnoOf
101
+ } from "./index-jj9228tt.js";
102
+ import {
103
+ AppError2
104
+ } from "./index-3pb4ccj2.js";
105
+ import {
106
+ isRecord,
107
+ isAsyncIterable
108
+ } from "./index-ps3djm8d.js";
109
+
110
+ // src/tools/cli/io.ts
111
+ import { writeSync } from "node:fs";
112
+
113
+ // src/tools/cli/stdin.ts
114
+ function readPipedStdin(input = process.stdin) {
115
+ if (input.isTTY || input.readableEnded)
116
+ return Promise.resolve(null);
117
+ if (input.destroyed)
118
+ return Promise.reject(new Error("stdin closed before EOF"));
119
+ return new Promise((resolve, reject) => {
120
+ const chunks = [];
121
+ const cleanup = () => {
122
+ clearTimeout(timer);
123
+ input.pause();
124
+ input.off("data", onData);
125
+ input.off("end", onEnd);
126
+ input.off("error", onError);
127
+ input.off("close", onClose);
128
+ };
129
+ const onData = (chunk) => {
130
+ if (chunk.length === 0)
131
+ return;
132
+ clearTimeout(timer);
133
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
134
+ };
135
+ const onEnd = () => {
136
+ cleanup();
137
+ const text = Buffer.concat(chunks).toString("utf8").trim();
138
+ resolve(text.length > 0 ? text : null);
139
+ };
140
+ const onError = (error) => {
141
+ cleanup();
142
+ reject(error);
143
+ };
144
+ const onClose = () => onError(new Error("stdin closed before EOF"));
145
+ const timer = setTimeout(() => {
146
+ cleanup();
147
+ resolve(null);
148
+ }, 250);
149
+ input.on("end", onEnd);
150
+ input.on("error", onError);
151
+ input.on("close", onClose);
152
+ input.on("data", onData);
153
+ input.resume();
154
+ });
155
+ }
156
+
157
+ // src/tools/cli/io.ts
158
+ function isReaderGone(error) {
159
+ const code = errnoOf(error);
160
+ return code === "EPIPE" || code === "ERR_STREAM_DESTROYED";
161
+ }
162
+ function createCliIo(config) {
163
+ let pendingWrite;
164
+ let writeFailed = false;
165
+ const writeFd = (fd, text) => {
166
+ const bytes = Buffer.from(text, "utf8");
167
+ let offset = 0;
168
+ while (offset < bytes.length) {
169
+ try {
170
+ offset += writeSync(fd, bytes, offset, bytes.length - offset);
171
+ } catch (error) {
172
+ if (fd === 1 && isReaderGone(error))
173
+ throw error;
174
+ if (errnoOf(error) === "EAGAIN") {
175
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1);
176
+ continue;
177
+ }
178
+ const stream = fd === 1 ? process.stdout : process.stderr;
179
+ const rest = bytes.subarray(offset);
180
+ pendingWrite = new Promise((resolve) => {
181
+ stream.write(rest, (failure) => {
182
+ if (failure)
183
+ writeFailed = true;
184
+ resolve();
185
+ });
186
+ });
187
+ return;
188
+ }
189
+ }
190
+ };
191
+ const writeStdout = config.stdout ?? ((text) => writeFd(1, text));
192
+ let readerGone = false;
193
+ const stdoutWhileOpen = (text) => {
194
+ if (readerGone)
195
+ return false;
196
+ try {
197
+ writeStdout(text);
198
+ return true;
199
+ } catch (error) {
200
+ if (!isReaderGone(error))
201
+ throw error;
202
+ readerGone = true;
203
+ return false;
204
+ }
205
+ };
206
+ const stdout = (text) => {
207
+ stdoutWhileOpen(text);
208
+ };
209
+ const stderr = config.stderr ?? ((text) => writeFd(2, text));
210
+ const exit = config.exit ?? ((code) => {
211
+ if (pendingWrite === undefined)
212
+ process.exit(code);
213
+ else
214
+ pendingWrite.then(() => process.exit(writeFailed ? 1 : code));
215
+ });
216
+ const readStdin = config.stdin ?? readPipedStdin;
217
+ return { stdout, stdoutWhileOpen, stderr, exit, readStdin };
218
+ }
219
+
220
+ // src/tools/cli/notices.ts
221
+ import { AsyncLocalStorage } from "node:async_hooks";
222
+ var invocationNotices = new AsyncLocalStorage;
223
+ function withCliNotices(quiet, stderr, run) {
224
+ return invocationNotices.run({ quiet, stderr }, run);
225
+ }
226
+ function writeCliNotice(text) {
227
+ const invocation = invocationNotices.getStore();
228
+ if (invocation !== undefined) {
229
+ if (!invocation.quiet)
230
+ invocation.stderr(text);
231
+ return;
232
+ }
233
+ const scan = scanCliInvocation2(process.argv.slice(2));
234
+ if (scan.error !== undefined || scan.framework.quiet)
235
+ return;
236
+ process.stderr.write(text);
237
+ }
238
+
239
+ // src/tools/cli/download.ts
240
+ import { createHash } from "node:crypto";
241
+ import { basename as basename2, resolve } from "node:path";
242
+
243
+ // src/internal/write-download.ts
244
+ import path from "node:path";
245
+ async function writeDownload(root, name, data) {
246
+ if (!isSafeEntryName(name) || path.basename(name) !== name) {
247
+ throw new Error("download name escapes the output dir");
248
+ }
249
+ const parent = { handle: root, basename: name };
250
+ const metadata = await containedEntryMetadata(parent);
251
+ await writeContainedFile({
252
+ parent,
253
+ content: data,
254
+ replace: true,
255
+ ...metadata?.isFile() && { mode: metadata.mode }
256
+ });
257
+ }
258
+
259
+ // src/tools/cli/inline-files.ts
260
+ import { basename } from "node:path";
261
+ import { pathToFileURL } from "node:url";
262
+ import { z } from "zod";
263
+ var EmbeddedResourceSchema = z.object({
264
+ type: z.literal("resource"),
265
+ resource: z.union([
266
+ z.object({ uri: z.string(), mimeType: z.string().optional(), blob: z.string() }),
267
+ z.object({ uri: z.string(), mimeType: z.string().optional(), text: z.string() })
268
+ ])
269
+ });
270
+ var InlineFileSchema = z.discriminatedUnion("type", [
271
+ McpImageContentSchema,
272
+ McpAudioContentSchema,
273
+ EmbeddedResourceSchema
274
+ ]);
275
+ function inlineFileBlocks(data) {
276
+ if (!isRecord(data) || !Array.isArray(data.content))
277
+ return [];
278
+ return data.content.flatMap((part, index) => {
279
+ const parsed = InlineFileSchema.safeParse(part);
280
+ return parsed.success ? [{ index, file: parsed.data }] : [];
281
+ });
282
+ }
283
+ function decodeBase64(data, maxBytes) {
284
+ const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
285
+ const decodedLength = Math.floor((data.length - padding) * 3 / 4);
286
+ if (data.length > Math.ceil(maxBytes / 3) * 4 || decodedLength > maxBytes) {
287
+ throw new Error(`file exceeds the ${maxBytes}-byte cap`);
288
+ }
289
+ if (data.length % 4 === 1 || padding > 0 && data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(data)) {
290
+ throw new Error("invalid base64");
291
+ }
292
+ const bytes = Buffer.from(data, "base64");
293
+ if (!bytes.toString("base64").startsWith(data))
294
+ throw new Error("invalid base64");
295
+ return bytes;
296
+ }
297
+ function encodeText(text, maxBytes) {
298
+ const bytes = text.length > maxBytes ? undefined : Buffer.from(text, "utf8");
299
+ if (!bytes || bytes.length > maxBytes) {
300
+ throw new Error(`file exceeds the ${maxBytes}-byte cap`);
301
+ }
302
+ return bytes;
303
+ }
304
+ function inlineFileBytes(file, maxBytes) {
305
+ if (file.type !== "resource")
306
+ return decodeBase64(file.data, maxBytes);
307
+ return "blob" in file.resource ? decodeBase64(file.resource.blob, maxBytes) : encodeText(file.resource.text, maxBytes);
308
+ }
309
+ function uriFileName(uri) {
310
+ try {
311
+ return basename(new URL(uri).pathname);
312
+ } catch {
313
+ return "";
314
+ }
315
+ }
316
+ function inlineFileMimeType(file) {
317
+ return file.type === "resource" ? file.resource.mimeType : file.mimeType;
318
+ }
319
+ function ownFileName(file) {
320
+ if (file.type === "resource")
321
+ return uriFileName(file.resource.uri) || undefined;
322
+ const name = file._meta?.[MCP_FILE_NAME_META_KEY2];
323
+ return typeof name === "string" ? name : undefined;
324
+ }
325
+ function inlineFileName(file, digest) {
326
+ return ownFileName(file) ?? `${file.type}-${digest}${mediaExtension(inlineFileMimeType(file) ?? "") ?? ".bin"}`;
327
+ }
328
+ function linkSavedFiles(data, blocks, saved) {
329
+ if (!isRecord(data) || !Array.isArray(data.content))
330
+ return data;
331
+ const links = new Map;
332
+ for (const block of blocks) {
333
+ const file = saved(block);
334
+ if (!file)
335
+ continue;
336
+ const mimeType = inlineFileMimeType(block.file);
337
+ links.set(block.index, {
338
+ type: "resource_link",
339
+ uri: pathToFileURL(file.path).href,
340
+ name: file.name,
341
+ ...mimeType !== undefined && { mimeType },
342
+ size: file.size
343
+ });
344
+ }
345
+ if (links.size === 0)
346
+ return data;
347
+ return { ...data, content: data.content.map((part, index) => links.get(index) ?? part) };
348
+ }
349
+
350
+ // src/tools/cli/download.ts
351
+ var DEFAULT_DOWNLOAD_MAX_BYTES = 100 * 1024 * 1024;
352
+ async function saveResultMedia(data, options) {
353
+ const blocks = inlineFileBlocks(data);
354
+ const sources = [...options.download?.(data) ?? [], ...blocks];
355
+ if (sources.length === 0) {
356
+ if (!options.quiet)
357
+ options.stderr(`--output-dir: the result carries no files to save
358
+ `);
359
+ return { ok: true, data };
360
+ }
361
+ const batch = await saveBatch(sources, options);
362
+ return {
363
+ ok: batch.ok,
364
+ data: linkSavedFiles(data, blocks, (block) => batch.files.get(block))
365
+ };
366
+ }
367
+ async function saveBatch(sources, { dir, allowPrivateHosts, maxBytes, timeoutMs, quiet, stderr }) {
368
+ const root = resolve(dir);
369
+ const files = new Map;
370
+ let directory;
371
+ try {
372
+ directory = await openPinnedDirectory(root, { create: true, readable: false });
373
+ } catch (error) {
374
+ stderr(`failed to prepare download directory: ${error instanceof Error ? error.message : String(error)}
375
+ `);
376
+ return { ok: false, files };
377
+ }
378
+ let ok = true;
379
+ const digests = new Map;
380
+ try {
381
+ for (const source of sources) {
382
+ try {
383
+ const bytes = "url" in source ? await fetchDownload(source.url, allowPrivateHosts, maxBytes, timeoutMs) : inlineFileBytes(source.file, maxBytes);
384
+ const digest = createHash("sha256").update(bytes).digest("hex");
385
+ const name = basename2("url" in source ? source.name : inlineFileName(source.file, digest));
386
+ const path = resolve(root, name);
387
+ const written = digests.get(name);
388
+ if (written === undefined) {
389
+ await writeDownload(directory, name, bytes);
390
+ digests.set(name, digest);
391
+ if (!quiet)
392
+ stderr(`saved ${path} (${(bytes.length / 1024).toFixed(0)}KB)
393
+ `);
394
+ } else if (written !== digest) {
395
+ throw new Error(`another file of this batch is already saved as ${JSON.stringify(name)}`);
396
+ }
397
+ files.set(source, { path, name, size: bytes.length });
398
+ } catch (err) {
399
+ ok = false;
400
+ const reason = errnoOf(err) ?? (err instanceof Error ? err.message : String(err));
401
+ const subject = "url" in source ? `failed to download ${source.url}` : `failed to save content[${source.index}]`;
402
+ stderr(`${subject}: ${reason}
403
+ `);
404
+ }
405
+ }
406
+ } finally {
407
+ try {
408
+ await directory.close();
409
+ } catch (error) {
410
+ ok = false;
411
+ stderr(`failed to close download directory: ${error instanceof Error ? error.message : String(error)}
412
+ `);
413
+ }
414
+ }
415
+ return { ok, files };
416
+ }
417
+ async function fetchDownload(url, allowPrivateHosts, maxBytes, timeoutMs) {
418
+ const res = await fetchGuarded(new URL(url), allowPrivateHosts, { timeoutMs });
419
+ if (!res.ok)
420
+ throw new Error(`HTTP ${res.status}`);
421
+ const bytes = await readCapped(res, maxBytes);
422
+ if (!bytes)
423
+ throw new Error(`file exceeds the ${maxBytes}-byte cap`);
424
+ return bytes;
425
+ }
426
+
427
+ // src/tools/cli/help.ts
428
+ var GLOBAL_OPTIONS = [
429
+ ["--json", "Emit compact success/error JSON records (for scripts)"],
430
+ ["--wait", "Block-poll an async result to a terminal state"],
431
+ ["--wait-timeout <s>", "Override the --wait timeout in seconds"],
432
+ ["--output-dir <dir>", "Save the files a result names or carries into a directory"],
433
+ ["--quiet", "Suppress non-essential stderr output"],
434
+ ["--dry-run", "Print the resolved call without executing it"],
435
+ ["--schema", "Print the JSON Schema of a command input and output"],
436
+ ["--help, -h", "Show help for a command"],
437
+ ["--help <text>", "List only the commands matching a substring"],
438
+ ["--count-by <field>", "Count records per distinct value of a field"],
439
+ ["--sum <field>", "Total a numeric field, optionally grouped by --by"],
440
+ ["--sort <field>", "Order the records by a field, largest first"],
441
+ ["--ascending", "Flip --sort to smallest first"],
442
+ ["--top <n>", "Keep the n leading entries of the view asked for"],
443
+ ["--table <a,b>", "Render the named fields as an aligned table"]
444
+ ];
445
+ function typeLabel(schema) {
446
+ if (HELP_SHOWN_KEYWORDS.has("enum") && Array.isArray(schema.enum)) {
447
+ return schema.enum.join("|");
448
+ }
449
+ if (HELP_SHOWN_KEYWORDS.has("type")) {
450
+ if (schema.type === "array")
451
+ return "value";
452
+ if (typeof schema.type === "string")
453
+ return schema.type;
454
+ }
455
+ return "value";
456
+ }
457
+ function isPatternOnly(member) {
458
+ return isRecord(member) && typeof member.pattern === "string" && Object.keys(member).every((key) => key === "pattern" || key === "type");
459
+ }
460
+ function constraintLabel(schema) {
461
+ const limits = [];
462
+ const format = HELP_SHOWN_KEYWORDS.has("format") && typeof schema.format === "string" ? schema.format : undefined;
463
+ const pattern = HELP_SHOWN_KEYWORDS.has("pattern") && typeof schema.pattern === "string" ? schema.pattern : undefined;
464
+ const named = format !== undefined && STANDARD_STRING_FORMATS.has(format);
465
+ if (format !== undefined && (named || pattern === undefined)) {
466
+ limits.push(format);
467
+ } else if (pattern !== undefined) {
468
+ limits.push(`pattern /${pattern}/`);
469
+ }
470
+ const bounds = [
471
+ ["minimum", ">="],
472
+ ["exclusiveMinimum", ">"],
473
+ ["maximum", "<="],
474
+ ["exclusiveMaximum", "<"],
475
+ ["minLength", "length >="],
476
+ ["maxLength", "length <="],
477
+ ["minItems", "items >="],
478
+ ["maxItems", "items <="]
479
+ ];
480
+ for (const [keyword, label] of bounds) {
481
+ if (!HELP_SHOWN_KEYWORDS.has(keyword))
482
+ continue;
483
+ const bound = schema[keyword];
484
+ if (typeof bound !== "number")
485
+ continue;
486
+ if (schema.type === "integer" && Math.abs(bound) === Number.MAX_SAFE_INTEGER)
487
+ continue;
488
+ limits.push(`${label}${bound}`);
489
+ }
490
+ const compositions = [
491
+ ["anyOf", "any of", " | "],
492
+ ["oneOf", "one of", " | "],
493
+ ["allOf", "all of", " & "]
494
+ ];
495
+ for (const [keyword, label, separator] of compositions) {
496
+ if (!HELP_SHOWN_KEYWORDS.has(keyword))
497
+ continue;
498
+ const members = schema[keyword];
499
+ if (!Array.isArray(members))
500
+ continue;
501
+ const stated = named && keyword === "allOf" ? members.filter((member) => !isPatternOnly(member)) : members;
502
+ const branches = stated.map((member) => {
503
+ const constraints = isRecord(member) ? constraintLabel(member) : "";
504
+ const type = isRecord(member) ? typeLabel(member) : member === false ? "no value" : "any value";
505
+ return { constraints, text: `${type}${constraints}` };
506
+ });
507
+ if (branches.every((branch) => branch.constraints === ""))
508
+ continue;
509
+ limits.push(`${label}: ${branches.map((branch) => branch.text).join(separator)}`);
510
+ }
511
+ return limits.length === 0 ? "" : ` [${limits.join(", ")}]`;
512
+ }
513
+ function fieldTypeLabel(schema) {
514
+ return `<${typeLabel(schema)}>${constraintLabel(schema)}`;
515
+ }
516
+ function nullableField(schema) {
517
+ if (schema.type === "null")
518
+ return true;
519
+ if (Array.isArray(schema.type) && schema.type.includes("null"))
520
+ return true;
521
+ return Array.isArray(schema.anyOf) && schema.anyOf.some((member) => isRecord(member) && nullableField(member));
522
+ }
523
+ function jsonValueHelp(fields) {
524
+ const example = fields.find((field) => nullableField(field.schema))?.name;
525
+ return [
526
+ "Assign a whole JSON value with --field:=JSON; the declared schema still validates it.",
527
+ ...example === undefined ? [] : [`JSON null: --${example}:=null. The literal string stays --${example} null.`]
528
+ ];
529
+ }
530
+ function padRight(text, width) {
531
+ return text.length >= width ? text : text + " ".repeat(width - text.length);
532
+ }
533
+ function summarize(desc) {
534
+ const firstLine = desc.split(`
535
+ `)[0]?.trim() ?? "";
536
+ const firstSentence = firstLine.split(". ")[0]?.trim() ?? firstLine;
537
+ const max = 72;
538
+ return firstSentence.length > max ? `${firstSentence.slice(0, max - 1).trimEnd()}…` : firstSentence;
539
+ }
540
+ function applicationOptionLines(fields) {
541
+ if (fields.length === 0)
542
+ return [];
543
+ const labels = new Map(fields.map((field) => [field.name, `--${field.name} ${fieldTypeLabel(field.schema)}`]));
544
+ const width = Math.max(...fields.map((field) => labels.get(field.name)?.length ?? 0));
545
+ return [
546
+ "",
547
+ "Application options:",
548
+ ...fields.map((field) => ` ${padRight(labels.get(field.name) ?? `--${field.name}`, width)} ${field.description ?? ""}`.trimEnd())
549
+ ];
550
+ }
551
+ function filterCommands(commands, filter) {
552
+ const needle = filter.toLowerCase();
553
+ return new Map([...commands].filter(([command, descriptor]) => command.toLowerCase().includes(needle) || descriptor.description.toLowerCase().includes(needle)));
554
+ }
555
+ function renderTopHelp(input) {
556
+ const { name, version, defaultCommand } = input;
557
+ const commands = input.filter === undefined ? input.commands : filterCommands(input.commands, input.filter);
558
+ const lines = [
559
+ `${name} ${version}`,
560
+ "",
561
+ `Usage: ${name} ${defaultCommand ? "[command]" : "<command>"} [args] [--flags]`,
562
+ "",
563
+ input.filter === undefined ? "Commands:" : `Commands matching "${input.filter}" (${commands.size} of ${input.commands.size}):`
564
+ ];
565
+ const width = Math.max(0, ...[...commands.keys()].map((key) => key.length));
566
+ for (const [command, descriptor] of commands) {
567
+ lines.push(` ${padRight(command, width)} ${summarize(descriptor.description)}${command === defaultCommand ? " (default)" : ""}${descriptor.unavailableReason !== undefined ? " [unavailable]" : ""}`);
568
+ if (descriptor.unavailableReason !== undefined) {
569
+ lines.push(` Unavailable: ${descriptor.unavailableReason}`);
570
+ }
571
+ }
572
+ if (input.unavailable !== undefined) {
573
+ lines.push("", `Managed commands are unavailable: ${input.unavailable}`);
574
+ }
575
+ if (input.filter !== undefined) {
576
+ lines.push("", `Run "${name} <command> --help" for command-specific flags.`);
577
+ return `${lines.join(`
578
+ `)}
579
+ `;
580
+ }
581
+ lines.push("", "Global options:");
582
+ const optWidth = Math.max(...GLOBAL_OPTIONS.map(([flag]) => flag.length));
583
+ for (const [flag, desc] of GLOBAL_OPTIONS)
584
+ lines.push(` ${padRight(flag, optWidth)} ${desc}`);
585
+ lines.push(...applicationOptionLines(input.applicationOptions));
586
+ lines.push("", ...jsonValueHelp(input.applicationOptions));
587
+ lines.push("", `Run "${name} <command> --help" for command-specific flags.`);
588
+ return `${lines.join(`
589
+ `)}
590
+ `;
591
+ }
592
+ function renderCommandHelp(name, command, descriptor, applicationOptions = []) {
593
+ const fields = jsonSchemaFields(descriptor.presentationSchema);
594
+ const fieldsByName = new Map(fields.map((field) => [field.name, field]));
595
+ const kinds = describeSchemaFields(descriptor.argumentSchema);
596
+ const positionals = [];
597
+ const positionalNames = descriptor.positionals ?? [...kinds].filter(([, info]) => info.kind !== "boolean").map(([fieldName]) => fieldName);
598
+ for (const fieldName of positionalNames) {
599
+ const field = fieldsByName.get(fieldName);
600
+ if (field)
601
+ positionals.push(field);
602
+ }
603
+ const variadicTail = descriptor.positionals !== undefined && kinds.get(descriptor.positionals[descriptor.positionals.length - 1] ?? "")?.kind === "array" ? descriptor.positionals[descriptor.positionals.length - 1] : undefined;
604
+ const positionalSyntax = new Map(positionals.map((field) => {
605
+ const label = field.name === variadicTail ? `${field.name}...` : field.name;
606
+ return [field.name, field.required ? `<${label}>` : `[${label}]`];
607
+ }));
608
+ const usage = [
609
+ `Usage: ${name} ${command}`,
610
+ ...positionals.map((field) => positionalSyntax.get(field.name) ?? field.name),
611
+ "[--flags]"
612
+ ].join(" ");
613
+ const lines = [descriptor.description, "", usage, ""];
614
+ if (descriptor.unavailableReason !== undefined) {
615
+ lines.push(`Unavailable: ${descriptor.unavailableReason}`, "");
616
+ }
617
+ if (fields.length > 0) {
618
+ lines.push("Arguments:");
619
+ const labels = new Map(fields.map((field) => {
620
+ const positional = positionalSyntax.get(field.name);
621
+ const alias = descriptor.aliases.get(field.name);
622
+ const option = alias ? `-${alias}, --${field.name}` : `--${field.name}`;
623
+ return [field.name, positional ? `${positional} | ${option}` : option];
624
+ }));
625
+ const width = Math.max(...fields.map((field) => labels.get(field.name)?.length ?? 0));
626
+ for (const f of fields) {
627
+ const req = f.required ? " (required)" : "";
628
+ const desc = f.description ? ` — ${f.description}` : "";
629
+ const label = labels.get(f.name) ?? `--${f.name}`;
630
+ lines.push(` ${padRight(label, width)} ${fieldTypeLabel(f.schema)}${req}${desc}`);
631
+ }
632
+ const flag = [...kinds].find(([, info]) => info.kind === "boolean")?.[0];
633
+ if (flag !== undefined) {
634
+ lines.push("", `A boolean flag is on alone or takes true/false: --${flag}, --${flag} false, --no-${flag}`);
635
+ }
636
+ const arrays = [...kinds].filter(([, info]) => info.kind === "array");
637
+ for (const [field] of arrays) {
638
+ lines.push("", `Repeat --${field} <value> for each element, or assign the whole array with --${field}:=JSON.`);
639
+ }
640
+ if (arrays.length > 0 && descriptor.positionals === undefined) {
641
+ lines.push("Array options cannot be combined with automatic positional arguments; name other fields with flags.");
642
+ }
643
+ lines.push("", ...jsonValueHelp(fields), "");
644
+ }
645
+ const applicationLines = applicationOptionLines(applicationOptions);
646
+ if (applicationLines.length > 0)
647
+ lines.push(...applicationLines.slice(1), "");
648
+ return `${lines.join(`
649
+ `)}
650
+ `;
651
+ }
652
+
653
+ // src/tools/cli/args-tokens.ts
654
+ function readCliTokens(argv, fields, fieldFor, config) {
655
+ const fwState = {
656
+ fw: { json: false, wait: false, quiet: false, dryRun: false, help: false, schema: false },
657
+ fwFlags: new Map,
658
+ viewFlags: new Map,
659
+ ascending: false
660
+ };
661
+ const flags = new Map;
662
+ const jsonFields = new Set;
663
+ const literalBooleanFlags = new Set;
664
+ const positionals = [];
665
+ const pushFlag = (name, value, json = false) => {
666
+ appendCliFieldValue(flags, jsonFields, name, value, fieldFor(name), json);
667
+ };
668
+ const adjacent = (index) => !config.separatedBefore?.has(index);
669
+ let optionsEnded = false;
670
+ for (let i = 0;i < argv.length; i++) {
671
+ const tok = argv[i];
672
+ if (tok === undefined)
673
+ continue;
674
+ if (!optionsEnded && tok === "--") {
675
+ optionsEnded = true;
676
+ continue;
677
+ }
678
+ if (optionsEnded || !looksLikeOption(tok)) {
679
+ positionals.push(tok);
680
+ continue;
681
+ }
682
+ if (tok === "-h") {
683
+ fwState.fw.help = true;
684
+ continue;
685
+ }
686
+ if (!tok.startsWith("--")) {
687
+ const match = /^-([A-Za-z])(?:=(.*))?$/.exec(tok);
688
+ const alias = match?.[1];
689
+ const field = alias === undefined ? undefined : config.aliases?.get(alias);
690
+ if (!alias || !field)
691
+ throw new CliArgumentError2(`Unknown option "${tok}"`);
692
+ const inline = match?.[2];
693
+ const info = fieldFor(field);
694
+ if (info?.kind === "boolean") {
695
+ const separate = inline === undefined && adjacent(i + 1) ? separateBoolValue(argv[i + 1]) : undefined;
696
+ if (separate !== undefined)
697
+ i++;
698
+ pushFlag(field, inline ?? String(separate ?? true));
699
+ if (inline !== undefined && info.pureBoolean === true) {
700
+ parseReservedBool(field, inline);
701
+ }
702
+ literalBooleanFlags.add(field);
703
+ continue;
704
+ }
705
+ let value = inline;
706
+ if (value === undefined) {
707
+ const next = adjacent(i + 1) ? argv[i + 1] : undefined;
708
+ if (next !== undefined && !isOptionToken(next)) {
709
+ value = next;
710
+ i++;
711
+ } else {
712
+ throw new CliArgumentError2(`--${field} requires a value`);
713
+ }
714
+ }
715
+ pushFlag(field, value);
716
+ continue;
717
+ }
718
+ const option = classifyLongOptionToken(tok);
719
+ if (!option)
720
+ throw new CliArgumentError2(`Unknown option "${tok}"`);
721
+ const { name, json } = cliFieldOption(option, fields);
722
+ let { value } = option;
723
+ if (name.length === 0)
724
+ throw new CliArgumentError2("Invalid empty option name");
725
+ if (json && RESERVED_CLI_OPTIONS.has(name)) {
726
+ throw new CliArgumentError2(`--${name} is a framework option and does not accept :=JSON`);
727
+ }
728
+ if (option.globalKind !== undefined) {
729
+ i = consumeFrameworkOptionToken(argv, i, option, fwState, {
730
+ adjacent,
731
+ onError: (error) => {
732
+ throw error;
733
+ }
734
+ });
735
+ continue;
736
+ }
737
+ if (value === undefined && name.startsWith("no-") && !fieldFor(name) && fieldFor(name.slice(3))?.kind === "boolean") {
738
+ pushFlag(name.slice(3), "false");
739
+ literalBooleanFlags.add(name.slice(3));
740
+ continue;
741
+ }
742
+ const unsafeSegment = name.split(".").find(isUnsafeKey);
743
+ if (unsafeSegment !== undefined) {
744
+ throw new CliArgumentError2(`Unsafe option name "--${name}"`);
745
+ }
746
+ const info = fieldFor(name);
747
+ const rootName = name.split(".")[0] ?? name;
748
+ if (!fields.has(rootName) && !config.allowUnknown) {
749
+ throw new CliArgumentError2(`Unknown option "--${name}"`);
750
+ }
751
+ if (value === undefined) {
752
+ if (info?.kind === "boolean") {
753
+ const separate = adjacent(i + 1) ? separateBoolValue(argv[i + 1]) : undefined;
754
+ if (separate !== undefined)
755
+ i++;
756
+ pushFlag(name, String(separate ?? true));
757
+ literalBooleanFlags.add(name);
758
+ continue;
759
+ }
760
+ const next = adjacent(i + 1) ? argv[i + 1] : undefined;
761
+ if (next !== undefined && !isOptionToken(next)) {
762
+ value = next;
763
+ i++;
764
+ } else {
765
+ throw new CliArgumentError2(`--${name} requires a value`);
766
+ }
767
+ }
768
+ pushFlag(name, value, json);
769
+ if (option.inline && !json && info?.kind === "boolean" && info.pureBoolean === true) {
770
+ parseReservedBool(name, value);
771
+ }
772
+ }
773
+ const { fw } = fwState;
774
+ const options = {
775
+ json: fw.json,
776
+ wait: fw.wait,
777
+ quiet: fw.quiet,
778
+ dryRun: fw.dryRun,
779
+ help: fw.help,
780
+ schema: fw.schema,
781
+ ...fw.waitTimeout !== undefined && { waitTimeout: fw.waitTimeout },
782
+ ...fw.outputDir !== undefined && { outputDir: fw.outputDir }
783
+ };
784
+ return {
785
+ options,
786
+ flags,
787
+ jsonFields,
788
+ literalBooleanFlags,
789
+ viewFlags: fwState.viewFlags,
790
+ ascending: fwState.ascending,
791
+ positionals
792
+ };
793
+ }
794
+
795
+ // src/tools/cli/args.ts
796
+ function buildToolArgs(tokens, fields, fieldFor, declaredPositionals, allowUnknown) {
797
+ const { flags, jsonFields, literalBooleanFlags, positionals } = tokens;
798
+ if (declaredPositionals === undefined && positionals.length > 0) {
799
+ const arrayFlag = [...flags.keys()].find((key) => fieldFor(key)?.kind === "array");
800
+ if (arrayFlag !== undefined) {
801
+ 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.`);
802
+ }
803
+ }
804
+ const toolArgs = {};
805
+ const fillable = declaredPositionals === undefined ? [...fields.entries()].filter(([, info]) => info.kind !== "boolean").map(([name]) => name) : [...declaredPositionals];
806
+ const variadicTail = declaredPositionals !== undefined && fields.get(fillable[fillable.length - 1] ?? "")?.kind === "array" ? fillable[fillable.length - 1] : undefined;
807
+ let pi = 0;
808
+ for (const key of fillable) {
809
+ if (pi >= positionals.length)
810
+ break;
811
+ if (key === variadicTail) {
812
+ if (flags.has(key)) {
813
+ throw new CliArgumentError2(`--${key} conflicts with the positional values for "${key}" — pass one form, not both`);
814
+ }
815
+ toolArgs[key] = coerceField(fields.get(key), positionals.slice(pi), `<${key}>`);
816
+ pi = positionals.length;
817
+ break;
818
+ }
819
+ if (flags.has(key))
820
+ continue;
821
+ const value = positionals[pi++];
822
+ if (value !== undefined) {
823
+ toolArgs[key] = coerceField(fields.get(key), [value], `<${key}>`);
824
+ }
825
+ }
826
+ if (pi < positionals.length) {
827
+ throw new CliArgumentError2(`Unexpected positional argument "${positionals[pi]}"`);
828
+ }
829
+ const dottedRoots = new Map;
830
+ for (const key of flags.keys()) {
831
+ const dot = key.indexOf(".");
832
+ const exactLiteralBoolean = literalBooleanFlags.has(key) && fields.has(key);
833
+ if (dot > 0 && !exactLiteralBoolean) {
834
+ dottedRoots.set(key.slice(0, dot), key);
835
+ }
836
+ }
837
+ for (const [root, dotted] of dottedRoots) {
838
+ if (flags.has(root)) {
839
+ throw new CliArgumentError2(`--${root} conflicts with --${dotted} — pass one form, not both`);
840
+ }
841
+ }
842
+ for (const key of jsonFields) {
843
+ for (const other of flags.keys()) {
844
+ if (other.startsWith(`${key}.`) || key.startsWith(`${other}.`)) {
845
+ throw new CliArgumentError2(`--${key} conflicts with --${other} — pass one form, not both`);
846
+ }
847
+ }
848
+ }
849
+ for (const [key, values] of flags) {
850
+ const info = fieldFor(key);
851
+ const exactLiteralBoolean = literalBooleanFlags.has(key) && fields.has(key);
852
+ if (key.includes(".") && !exactLiteralBoolean) {
853
+ const root = key.split(".")[0] ?? key;
854
+ const value = !jsonFields.has(key) && info === undefined && allowUnknown && !fields.has(root) ? looseCoerce(values[0] ?? "") : coerceCliFieldValue(info, values, `--${key}`, jsonFields.has(key));
855
+ setNested(toolArgs, key.split("."), value);
856
+ continue;
857
+ }
858
+ toolArgs[key] = coerceCliFieldValue(info, values, `--${key}`, jsonFields.has(key));
859
+ }
860
+ return toolArgs;
861
+ }
862
+ function cliRunOptions(framework) {
863
+ return {
864
+ json: framework.json,
865
+ wait: framework.wait,
866
+ quiet: framework.quiet,
867
+ dryRun: framework.dryRun,
868
+ help: framework.help,
869
+ schema: framework.schema,
870
+ ...framework.waitTimeout !== undefined && { waitTimeout: framework.waitTimeout },
871
+ ...framework.outputDir !== undefined && { outputDir: framework.outputDir },
872
+ ...framework.view !== undefined && { view: framework.view }
873
+ };
874
+ }
875
+ function parseCliArgs2(argv, schema, config = {}) {
876
+ try {
877
+ return parseCommandArgv(argv, schema, config);
878
+ } catch (error) {
879
+ if (!(error instanceof CliArgumentError2))
880
+ throw error;
881
+ const scan = scanCliArgv(argv, {
882
+ afterCommand: true,
883
+ separatedBefore: config.separatedBefore
884
+ });
885
+ if (!answersBeforeArguments(scan))
886
+ throw error;
887
+ return { toolArgs: {}, options: cliRunOptions(scan.framework) };
888
+ }
889
+ }
890
+ function parseCommandArgv(argv, schema, config) {
891
+ const fields = describeSchemaFields(schema);
892
+ for (const name of config.knownFields ?? []) {
893
+ if (!fields.has(name))
894
+ fields.set(name, { kind: "other" });
895
+ }
896
+ const fieldFor = (name) => fields.get(name) ?? (name.includes(".") ? describeSchemaPath(schema, name.split(".")) : undefined);
897
+ const tokens = readCliTokens(argv, fields, fieldFor, config);
898
+ const { options } = tokens;
899
+ const view = resolveCliView(tokens.viewFlags, tokens.ascending);
900
+ if (view)
901
+ options.view = view;
902
+ return {
903
+ toolArgs: buildToolArgs(tokens, fields, fieldFor, config.positionals, config.allowUnknown === true),
904
+ options
905
+ };
906
+ }
907
+ function extractCliGlobalOptions2(argv, schema) {
908
+ if (schema === undefined)
909
+ return { argv: [...argv], globals: {} };
910
+ let result;
911
+ try {
912
+ result = scanCliArgv(argv, { appGlobals: schema });
913
+ } catch (error) {
914
+ if (error instanceof CliArgumentError2) {
915
+ return { argv: [], globals: {}, error };
916
+ }
917
+ throw error;
918
+ }
919
+ const early = answersBeforeArguments(result);
920
+ const error = early ? undefined : result.appGlobalError ?? result.liftedBoundaryError;
921
+ if (error !== undefined) {
922
+ return {
923
+ argv: [],
924
+ globals: result.globals,
925
+ error
926
+ };
927
+ }
928
+ return {
929
+ argv: result.withoutGlobals,
930
+ globals: result.globals,
931
+ ...result.separatedBeforeGlobals.size > 0 && {
932
+ separatedBefore: result.separatedBeforeGlobals
933
+ }
934
+ };
935
+ }
936
+
937
+ // src/tools/cli/prepare.ts
938
+ function looseCoerceValue(value) {
939
+ if (Array.isArray(value))
940
+ return value.map(looseCoerceValue);
941
+ return typeof value === "string" ? looseCoerce(value) : value;
942
+ }
943
+ function passthroughBase(value) {
944
+ if (isRecord(value))
945
+ return value;
946
+ if (typeof value === "string") {
947
+ try {
948
+ const parsed = safeJsonParse(value);
949
+ if (isRecord(parsed))
950
+ return parsed;
951
+ } catch {}
952
+ }
953
+ return;
954
+ }
955
+ function collectPassthrough(toolArgs, field, knownKeys) {
956
+ const known = new Set(knownKeys);
957
+ const bag = {};
958
+ for (const key of Object.keys(toolArgs)) {
959
+ if (key === field || known.has(key))
960
+ continue;
961
+ bag[key] = looseCoerceValue(toolArgs[key]);
962
+ delete toolArgs[key];
963
+ }
964
+ if (Object.keys(bag).length === 0)
965
+ return;
966
+ const base = passthroughBase(toolArgs[field]);
967
+ toolArgs[field] = base ? { ...base, ...bag } : bag;
968
+ }
969
+ async function prepareInvocation(command, commandTokens, separatedBefore, framework, descriptor, config, readStdin) {
970
+ const passthroughField = cliPassthroughField(config, command);
971
+ let parsed;
972
+ try {
973
+ parsed = parseCliArgs2(commandTokens, descriptor.argumentSchema, {
974
+ allowUnknown: passthroughField !== undefined,
975
+ knownFields: jsonSchemaFields(descriptor.presentationSchema).map((field) => field.name),
976
+ aliases: new Map([...descriptor.aliases].map(([field, alias]) => [alias, field])),
977
+ positionals: descriptor.positionals,
978
+ separatedBefore
979
+ });
980
+ } catch (error) {
981
+ if (!(error instanceof CliArgumentError2))
982
+ throw error;
983
+ return { ok: false, message: error.message };
984
+ }
985
+ const { toolArgs } = parsed;
986
+ const options = cliRunOptions(framework);
987
+ const firstUnset = jsonSchemaFields(descriptor.presentationSchema).find((field) => field.required && !(field.name in toolArgs) && field.schema.type !== "boolean");
988
+ if (firstUnset) {
989
+ const piped = await readStdin();
990
+ if (piped !== null) {
991
+ if (descriptor.positionals === undefined) {
992
+ toolArgs[firstUnset.name] = piped;
993
+ } else {
994
+ const fieldInfo = describeSchemaFields(descriptor.argumentSchema).get(firstUnset.name);
995
+ try {
996
+ toolArgs[firstUnset.name] = coerceField(fieldInfo, [piped], `--${firstUnset.name}`);
997
+ } catch (error) {
998
+ if (!(error instanceof CliArgumentError2))
999
+ throw error;
1000
+ return { ok: false, message: error.message };
1001
+ }
1002
+ }
1003
+ }
1004
+ }
1005
+ if (passthroughField) {
1006
+ collectPassthrough(toolArgs, passthroughField, objectShapeKeys(descriptor.argumentSchema));
1007
+ }
1008
+ return { ok: true, toolArgs, options };
1009
+ }
1010
+
1011
+ // src/tools/cli/run-stream.ts
1012
+ async function runStreamCommand(session, route, managed, stream, { toolArgs, options }) {
1013
+ const { config } = session;
1014
+ const { stdout, stderr, exit } = session.io;
1015
+ const command = stream.tool.name;
1016
+ if (options.wait || options.outputDir !== undefined || options.view !== undefined) {
1017
+ stderr(`--wait, --output-dir and aggregate views do not apply to stream command "${command}"
1018
+ `);
1019
+ return exit(2);
1020
+ }
1021
+ const abort = new AbortController;
1022
+ let cancelled = false;
1023
+ const cancel = () => {
1024
+ cancelled = true;
1025
+ abort.abort(config.signal?.reason);
1026
+ };
1027
+ if (config.signal?.aborted)
1028
+ cancel();
1029
+ else
1030
+ config.signal?.addEventListener("abort", cancel, { once: true });
1031
+ const runTool = createCliToolRunner(config, session.lifecycle, managed.auth, route.typedGlobals);
1032
+ let opened;
1033
+ try {
1034
+ opened = await runTool(stream.tool, toolArgs, { signal: abort.signal });
1035
+ } catch (error) {
1036
+ opened = toolResultFromError(error);
1037
+ }
1038
+ const policy = cliResultPolicy(config, command);
1039
+ let outcome;
1040
+ if (!opened.ok)
1041
+ outcome = opened;
1042
+ else if (!isAsyncIterable(opened.data)) {
1043
+ outcome = toolResultFromError(new Error(`Stream command "${command}" handler did not return an async iterable`));
1044
+ } else {
1045
+ outcome = await printStreamItems(opened.data, stream, abort, () => cancelled, (item) => session.io.stdoutWhileOpen(streamLine(command, item, policy, options, config.errors)));
1046
+ }
1047
+ config.signal?.removeEventListener("abort", cancel);
1048
+ if (outcome === "completed" || outcome === "reader-gone")
1049
+ return exit(0);
1050
+ if (outcome === "cancelled" || cancelled) {
1051
+ return exit(cliExitCode2(applyToolErrorMapping({ ok: false, code: "REQUEST_ABORTED" }, config.errors), config.exitCodes));
1052
+ }
1053
+ return exit(emitResult2(outcome, { stdout, stderr }, emitOptionsFor(config, options.json, command)));
1054
+ }
1055
+ function streamLine(command, item, policy, options, errors) {
1056
+ if (policy?.present === undefined)
1057
+ return `${stringifyJsonSafe(item)}
1058
+ `;
1059
+ let line;
1060
+ try {
1061
+ line = policy.present({ result: item, options });
1062
+ if (typeof line !== "string")
1063
+ throw new Error("CLI result presenter must return a string");
1064
+ } catch (error) {
1065
+ throw new AppError2("CLI_PRESENTATION_FAILED", {
1066
+ message: "A stream item was produced, but its presentation failed.",
1067
+ status: 500,
1068
+ details: {
1069
+ command,
1070
+ cause: formatToolError(applyToolErrorMapping(toolResultFromError(error), errors))
1071
+ }
1072
+ });
1073
+ }
1074
+ return line;
1075
+ }
1076
+ async function printStreamItems(source, { descriptor }, abort, wasCancelled, write) {
1077
+ const iterator = source[Symbol.asyncIterator]();
1078
+ let lifetimeExpired = false;
1079
+ const lifetime = descriptor.lifetimeMs === undefined ? undefined : setTimeout(() => {
1080
+ lifetimeExpired = true;
1081
+ abort.abort(new Error("Stream lifetime expired"));
1082
+ }, descriptor.lifetimeMs);
1083
+ lifetime?.unref?.();
1084
+ try {
1085
+ for await (const { item } of readContractStreamItems(iterator, descriptor, abort.signal)) {
1086
+ if (!write(item))
1087
+ return "reader-gone";
1088
+ }
1089
+ return "completed";
1090
+ } catch (error) {
1091
+ if (wasCancelled())
1092
+ return "cancelled";
1093
+ if (lifetimeExpired) {
1094
+ return toolResultFromError(contractStreamLifetimeExceeded());
1095
+ }
1096
+ return projectCliUnixFailure(toolResultFromError(error));
1097
+ } finally {
1098
+ if (lifetime !== undefined)
1099
+ clearTimeout(lifetime);
1100
+ abort.abort();
1101
+ Promise.resolve().then(() => iterator.return?.(undefined)).catch(() => {
1102
+ return;
1103
+ });
1104
+ }
1105
+ }
1106
+
1107
+ // src/tools/cli/wait.ts
1108
+ var DEFAULT_TIMEOUT = 600;
1109
+ function waitFailure(tool, result) {
1110
+ return {
1111
+ ok: false,
1112
+ code: "WAIT_FAILED",
1113
+ details: {
1114
+ message: `"${tool}" reached a terminal failed state`,
1115
+ result
1116
+ }
1117
+ };
1118
+ }
1119
+ async function pollUntilDone2(params) {
1120
+ const { initial, wait, call } = params;
1121
+ if (!initial.ok)
1122
+ return initial;
1123
+ if (wait.failed?.(initial.data))
1124
+ return waitFailure(wait.tool, initial.data);
1125
+ if (wait.done(initial.data))
1126
+ return initial;
1127
+ const pollArgs = wait.poll(initial.data);
1128
+ if (!pollArgs)
1129
+ return initial;
1130
+ const timeoutSec = params.timeoutSec ?? wait.timeout ?? DEFAULT_TIMEOUT;
1131
+ let failedState;
1132
+ const { state, timedOut } = await pollUntil({
1133
+ poll: () => call(wait.tool, pollArgs),
1134
+ done: (result) => {
1135
+ if (!result.ok)
1136
+ return true;
1137
+ if (wait.failed?.(result.data)) {
1138
+ failedState = result;
1139
+ return true;
1140
+ }
1141
+ return wait.done(result.data);
1142
+ },
1143
+ backoff: wait.backoff,
1144
+ timeoutSec,
1145
+ sleepFn: params.sleepFn,
1146
+ onTick: params.onTick,
1147
+ signal: params.signal
1148
+ });
1149
+ if (timedOut) {
1150
+ return {
1151
+ ok: false,
1152
+ code: "TIMEOUT",
1153
+ details: { message: `Timed out after ${timeoutSec}s waiting for "${wait.tool}"` }
1154
+ };
1155
+ }
1156
+ if (state === failedState && state.ok)
1157
+ return waitFailure(wait.tool, state.data);
1158
+ return state;
1159
+ }
1160
+
1161
+ // src/tools/cli/run-managed.ts
1162
+ async function runManagedInvocation(session, route) {
1163
+ const { config } = session;
1164
+ const { stdout, stderr, exit } = session.io;
1165
+ const { command, topLevelHelp, helpRequested, schemaRequested } = route;
1166
+ const managed = await buildManagedSurface(session, route.typedGlobals, !topLevelHelp && !helpRequested && !schemaRequested && !isInspectOnlyLifecycle(session.lifecycle));
1167
+ if (topLevelHelp || command === undefined)
1168
+ return respondTopLevelHelp(session, route, managed);
1169
+ if (!managed.resolved) {
1170
+ return exit(emitResult2(managed.failure, { stdout, stderr }, emitOptionsFor(config, route.framework.json, command)));
1171
+ }
1172
+ return runManagedCommand(session, route, command, managed);
1173
+ }
1174
+ function respondTopLevelHelp(session, route, managed) {
1175
+ const { config, applicationOptions } = session;
1176
+ const { stdout, stderr, exit } = session.io;
1177
+ const filter = route.helpFilter;
1178
+ if (filter !== undefined && filterCommands(managed.help, filter).size === 0) {
1179
+ stderr(`no command matches "${filter}" (${[...managed.help.values()].filter((entry) => entry.unavailableReason === undefined).length} available)
1180
+ ` + (managed.resolved ? "" : `Managed commands are unavailable: ${managed.reason}
1181
+ `));
1182
+ exit(cliExitCode2(applyToolErrorMapping({ ok: false, code: "NOT_FOUND" }, config.errors), config.exitCodes));
1183
+ return;
1184
+ }
1185
+ stdout(renderTopHelp({
1186
+ name: config.name,
1187
+ version: config.version,
1188
+ commands: managed.help,
1189
+ defaultCommand: config.defaultCommand,
1190
+ applicationOptions,
1191
+ ...filter !== undefined && { filter },
1192
+ ...managed.resolved ? {} : { unavailable: managed.reason }
1193
+ }));
1194
+ exit(0);
1195
+ }
1196
+ async function runManagedCommand(session, route, command, managed) {
1197
+ const { config, applicationOptions } = session;
1198
+ const { stdout, stderr, exit, readStdin } = session.io;
1199
+ const descriptor = managed.help.get(command);
1200
+ if (!descriptor) {
1201
+ stderr(`Unknown command "${command}". Run "${config.name} --help" for the command list.
1202
+ `);
1203
+ return exit(cliExitCode2(applyToolErrorMapping(unknownCliCommand(command), config.errors), config.exitCodes));
1204
+ }
1205
+ if (route.helpRequested) {
1206
+ stdout(renderCommandHelp(config.name, command, descriptor, applicationOptions));
1207
+ return exit(0);
1208
+ }
1209
+ if (route.schemaRequested) {
1210
+ stdout(renderCommandSchema(command, descriptor));
1211
+ return exit(0);
1212
+ }
1213
+ const inspectErr = inspectOnlyError(session.lifecycle);
1214
+ if (inspectErr) {
1215
+ return exit(emitResult2(toolResultFromError(inspectErr), { stdout, stderr }, emitOptionsFor(config, route.framework.json, command)));
1216
+ }
1217
+ if (descriptor.unavailableReason !== undefined) {
1218
+ return exit(emitResult2(unavailableCommand(descriptor.unavailableReason), { stdout, stderr }, emitOptionsFor(config, route.framework.json, command)));
1219
+ }
1220
+ const stream = managed.streams.get(command);
1221
+ const tool = managed.tools.get(command);
1222
+ if (!tool && !stream)
1223
+ throw new Error("[stitchkit] managed CLI executable invariant failed");
1224
+ const prepared = await prepareInvocation(command, route.commandTokens, route.separatedBefore, route.framework, descriptor, config, readStdin);
1225
+ if (!prepared.ok) {
1226
+ stderr(`${prepared.message}
1227
+ `);
1228
+ return exit(2);
1229
+ }
1230
+ const { toolArgs, options } = prepared;
1231
+ if (options.wait && !cliWaitConfig(config, command)) {
1232
+ stderr(`--wait is not configured for command "${command}"
1233
+ `);
1234
+ return exit(2);
1235
+ }
1236
+ if (options.waitTimeout !== undefined && !options.wait) {
1237
+ stderr(`--wait-timeout requires --wait
1238
+ `);
1239
+ return exit(2);
1240
+ }
1241
+ if (options.dryRun) {
1242
+ stdout(`${JSON.stringify({ command, args: toolArgs }, null, 2)}
1243
+ `);
1244
+ return exit(0);
1245
+ }
1246
+ if (stream)
1247
+ return runStreamCommand(session, route, managed, stream, { toolArgs, options });
1248
+ if (!tool)
1249
+ throw new Error("[stitchkit] managed CLI executable invariant failed");
1250
+ if (options.view !== undefined && !options.wait) {
1251
+ try {
1252
+ assertViewColumns(options.view, descriptor.outputSchema);
1253
+ } catch (error) {
1254
+ if (!(error instanceof CliArgumentError2))
1255
+ throw error;
1256
+ stderr(`${error.message}
1257
+ `);
1258
+ return exit(2);
1259
+ }
1260
+ }
1261
+ const result = await executeManagedTool(session, route, command, managed, tool, {
1262
+ toolArgs,
1263
+ options
1264
+ });
1265
+ return emitManagedResult(session, command, result, options, isRepeatableRead(tool.method));
1266
+ }
1267
+ async function executeManagedTool(session, route, command, managed, tool, { toolArgs, options }) {
1268
+ const { config } = session;
1269
+ const { stderr } = session.io;
1270
+ const runTool = createCliToolRunner(config, session.lifecycle, managed.auth, route.typedGlobals);
1271
+ let result;
1272
+ try {
1273
+ result = await runTool(tool, toolArgs);
1274
+ } catch (err) {
1275
+ result = toolResultFromError(err);
1276
+ }
1277
+ const waitConfig = cliWaitConfig(config, command);
1278
+ if (options.wait && waitConfig) {
1279
+ result = await pollUntilDone2({
1280
+ initial: result,
1281
+ wait: waitConfig,
1282
+ call: async (toolName, args) => {
1283
+ const unavailable = managed.help.get(toolName)?.unavailableReason;
1284
+ if (unavailable !== undefined)
1285
+ return unavailableCommand(unavailable);
1286
+ const pollTool = managed.tools.get(toolName);
1287
+ if (!pollTool) {
1288
+ return {
1289
+ ok: false,
1290
+ code: "UNKNOWN_OPERATION",
1291
+ details: {
1292
+ message: `--wait: no command "${toolName}" to poll`,
1293
+ operation: toolName
1294
+ }
1295
+ };
1296
+ }
1297
+ return runTool(pollTool, args);
1298
+ },
1299
+ timeoutSec: options.waitTimeout,
1300
+ onTick: options.quiet ? undefined : (attempt) => stderr(`waiting… (poll ${attempt})
1301
+ `),
1302
+ signal: config.signal
1303
+ });
1304
+ }
1305
+ return result;
1306
+ }
1307
+ async function emitManagedResult(session, command, result, options, repeatable) {
1308
+ const { config } = session;
1309
+ const { stdout, stderr, exit } = session.io;
1310
+ const emit = { ...emitOptionsFor(config, options.json, command), repeatable };
1311
+ if (!result.ok)
1312
+ return exit(emitResult2(result, { stdout, stderr }, emit));
1313
+ let shown = result;
1314
+ let mediaExitCode = 0;
1315
+ if (options.outputDir !== undefined) {
1316
+ const saved = await saveResultMedia(result.data, {
1317
+ dir: options.outputDir,
1318
+ download: config.download,
1319
+ allowPrivateHosts: config.allowPrivateDownloadHosts ?? false,
1320
+ maxBytes: config.maxDownloadBytes ?? DEFAULT_DOWNLOAD_MAX_BYTES,
1321
+ timeoutMs: config.downloadTimeoutMs,
1322
+ quiet: options.quiet,
1323
+ stderr
1324
+ });
1325
+ shown = { ...result, data: saved.data };
1326
+ if (!saved.ok)
1327
+ mediaExitCode = 1;
1328
+ }
1329
+ return exit(emitCliViewOrResult(cliResultPolicy(config, command), result, options, { stdout, stderr }, emit, shown, mediaExitCode));
1330
+ }
1331
+
1332
+ // src/tools/cli/run-native.ts
1333
+ async function runNativeCommand(session, route, command, native) {
1334
+ const { config, applicationOptions, nativeHelp } = session;
1335
+ const { stdout, stderr, exit, readStdin } = session.io;
1336
+ const { commandTokens, separatedBefore, framework, helpRequested, globals } = route;
1337
+ const descriptor = nativeHelp.get(command);
1338
+ if (!descriptor)
1339
+ throw new Error("[stitchkit] native CLI descriptor invariant failed");
1340
+ if (helpRequested) {
1341
+ stdout(renderCommandHelp(config.name, command, descriptor, applicationOptions));
1342
+ return exit(0);
1343
+ }
1344
+ if (route.schemaRequested) {
1345
+ stdout(renderCommandSchema(command, descriptor));
1346
+ return exit(0);
1347
+ }
1348
+ const prepared = await prepareInvocation(command, commandTokens, separatedBefore, framework, descriptor, config, readStdin);
1349
+ if (!prepared.ok) {
1350
+ stderr(`${prepared.message}
1351
+ `);
1352
+ return exit(2);
1353
+ }
1354
+ const { toolArgs, options } = prepared;
1355
+ if (options.wait) {
1356
+ stderr(`--wait is not configured for native command "${command}"
1357
+ `);
1358
+ return exit(2);
1359
+ }
1360
+ if (options.waitTimeout !== undefined) {
1361
+ stderr(`--wait-timeout requires --wait
1362
+ `);
1363
+ return exit(2);
1364
+ }
1365
+ if (options.outputDir !== undefined) {
1366
+ stderr(`--output-dir is not configured for native commands
1367
+ `);
1368
+ return exit(2);
1369
+ }
1370
+ if (options.dryRun) {
1371
+ stdout(`${JSON.stringify({ command, args: toolArgs }, null, 2)}
1372
+ `);
1373
+ return exit(0);
1374
+ }
1375
+ return exit(await executeNativeCommand(native, toolArgs, config.coerceJsonArgs ?? true, globals, {
1376
+ mode: "terminal",
1377
+ options,
1378
+ writers: { stdout, stderr },
1379
+ emit: { ...emitOptionsFor(config, options.json, command), repeatable: false }
1380
+ }));
1381
+ }
1382
+
1383
+ // src/tools/cli/create-cli.ts
1384
+ async function createCli2(config) {
1385
+ resolveOptionalCliToolAccess("createCli", config);
1386
+ assertErrorCodeMapping("createCli", config.errors);
1387
+ assertNoLegacyCliPolicyKeys(config);
1388
+ const io = createCliIo(config);
1389
+ const argv = config.argv ?? process.argv.slice(2);
1390
+ const session = createCliSession(config, io);
1391
+ const route = resolveCliRoute(session, argv);
1392
+ if (route === undefined)
1393
+ return;
1394
+ return withCliNotices(route.quiet, io.stderr, () => {
1395
+ const { command } = route;
1396
+ const native = command === undefined ? undefined : session.nativeCommands.get(command);
1397
+ if (native && command !== undefined) {
1398
+ return runNativeCommand(session, route, command, native);
1399
+ }
1400
+ return runManagedInvocation(session, route);
1401
+ });
1402
+ }
1403
+
1404
+ export { writeCliNotice, parseCliArgs2, extractCliGlobalOptions2, pollUntilDone2, createCli2 };