@mastra/core 1.86.0-alpha.7 → 1.86.0-alpha.9

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 (509) hide show
  1. package/dist/_types/@internal_core@0.1.4/dist/knowledge-compat/index.d.ts +363 -0
  2. package/dist/a2a/index.cjs +1 -1
  3. package/dist/a2a/index.js +1 -1
  4. package/dist/agent/agent.d.ts +72 -1
  5. package/dist/agent/agent.types.d.ts +30 -2
  6. package/dist/agent/durable/create-evented-agent.d.ts +6 -0
  7. package/dist/agent/durable/durable-agent.d.ts +1 -15
  8. package/dist/agent/durable/index.cjs +7 -26
  9. package/dist/agent/durable/index.js +7 -26
  10. package/dist/agent/durable/preparation.d.ts +2 -0
  11. package/dist/agent/durable/utils/resolve-runtime.d.ts +9 -0
  12. package/dist/agent/durable/workflows/durable-loop-builder.d.ts +4 -0
  13. package/dist/agent/durable/workflows/finalize-run.d.ts +3 -1
  14. package/dist/agent/durable/workflows/steps/llm-execution.d.ts +1 -0
  15. package/dist/agent/index.cjs +3 -3
  16. package/dist/agent/index.js +3 -3
  17. package/dist/agent/message-list/index.cjs +1 -1
  18. package/dist/agent/message-list/index.js +1 -1
  19. package/dist/agent/message-list/message-list.d.ts +11 -0
  20. package/dist/agent/message-list/utils/provider-compat.d.ts +1 -0
  21. package/dist/agent/request-context-snapshot.d.ts +1 -1
  22. package/dist/agent/streams/types.d.ts +10 -0
  23. package/dist/agent/thread-stream-runtime.d.ts +5 -0
  24. package/dist/agent/types.d.ts +25 -0
  25. package/dist/agent-builder/ee/index.cjs +1 -1
  26. package/dist/agent-builder/ee/index.js +1 -1
  27. package/dist/agent-controller/index.cjs +1 -1
  28. package/dist/agent-controller/index.js +1 -1
  29. package/dist/{agent-controller-K5vHtqfO.cjs → agent-controller-CrQ9OF80.cjs} +8 -8
  30. package/dist/{agent-controller-Cf3_IuY8.js → agent-controller-SSlKzE6A.js} +8 -8
  31. package/dist/background-tasks/index.cjs +1 -1
  32. package/dist/background-tasks/index.js +1 -1
  33. package/dist/{background-tasks-DqnQMfuf.cjs → background-tasks-BDrYBis-.cjs} +5 -3
  34. package/dist/{background-tasks-BgpX1P_s.js → background-tasks-BnJfNLFo.js} +5 -3
  35. package/dist/browser/index.cjs +2 -2
  36. package/dist/browser/index.js +2 -2
  37. package/dist/{builder-x295GDL6.js → builder-Cl-0BWkh.js} +2 -2
  38. package/dist/{builder-D8Osghdo.cjs → builder-Cw8u3pPl.cjs} +2 -2
  39. package/dist/capabilities/302ai.json +192 -192
  40. package/dist/capabilities/abliteratedllm.json +34 -34
  41. package/dist/capabilities/abliteration-ai.json +11 -11
  42. package/dist/capabilities/above.json +17 -17
  43. package/dist/capabilities/adaption.json +12 -12
  44. package/dist/capabilities/adzuki.json +30 -30
  45. package/dist/capabilities/agentrouter.json +10 -10
  46. package/dist/capabilities/agnes.json +4 -4
  47. package/dist/capabilities/ai-router.json +9 -9
  48. package/dist/capabilities/aiand.json +19 -11
  49. package/dist/capabilities/aigrow.json +11 -11
  50. package/dist/capabilities/aimlapi.json +146 -149
  51. package/dist/capabilities/aipg.json +2 -2
  52. package/dist/capabilities/aixy.json +14 -14
  53. package/dist/capabilities/aki-io.json +11 -11
  54. package/dist/capabilities/alibaba-cn.json +128 -109
  55. package/dist/capabilities/alibaba-coding-plan-cn.json +7 -19
  56. package/dist/capabilities/alibaba-coding-plan.json +7 -19
  57. package/dist/capabilities/alibaba-token-plan-cn.json +49 -67
  58. package/dist/capabilities/alibaba-token-plan.json +51 -69
  59. package/dist/capabilities/alibaba.json +71 -118
  60. package/dist/capabilities/ambient.json +14 -14
  61. package/dist/capabilities/amd.json +11 -11
  62. package/dist/capabilities/anthropic.json +48 -48
  63. package/dist/capabilities/anyapi.json +18 -18
  64. package/dist/capabilities/apiko.json +2 -2
  65. package/dist/capabilities/arcee.json +10 -10
  66. package/dist/capabilities/augure.json +6 -6
  67. package/dist/capabilities/auriko.json +20 -20
  68. package/dist/capabilities/bailing.json +5 -5
  69. package/dist/capabilities/baseten.json +46 -16
  70. package/dist/capabilities/bee.json +5 -5
  71. package/dist/capabilities/berget.json +4 -4
  72. package/dist/capabilities/bothub.json +16 -16
  73. package/dist/capabilities/boundless.json +36 -36
  74. package/dist/capabilities/bumo.json +40 -40
  75. package/dist/capabilities/byteplus.json +32 -32
  76. package/dist/capabilities/cerebras.json +4 -4
  77. package/dist/capabilities/cheapaimodel.json +5 -5
  78. package/dist/capabilities/cheapest-token.json +24 -24
  79. package/dist/capabilities/chutes.json +9 -9
  80. package/dist/capabilities/cline-pass.json +37 -37
  81. package/dist/capabilities/cloudcode.json +4 -4
  82. package/dist/capabilities/cloudflare-workers-ai.json +24 -24
  83. package/dist/capabilities/commandcode.json +152 -152
  84. package/dist/capabilities/concentrate.json +290 -266
  85. package/dist/capabilities/cortecs.json +105 -105
  86. package/dist/capabilities/crossmodel.json +160 -160
  87. package/dist/capabilities/crusoe.json +10 -10
  88. package/dist/capabilities/daoxe.json +7 -7
  89. package/dist/capabilities/databricks.json +318 -62
  90. package/dist/capabilities/deepinfra.json +73 -129
  91. package/dist/capabilities/deepseek.json +2 -2
  92. package/dist/capabilities/digitalocean.json +114 -114
  93. package/dist/capabilities/dothoosh.json +28 -28
  94. package/dist/capabilities/doubleword.json +24 -24
  95. package/dist/capabilities/edenai.json +458 -458
  96. package/dist/capabilities/empiriolabs.json +166 -166
  97. package/dist/capabilities/engy.json +20 -20
  98. package/dist/capabilities/evroc.json +8 -8
  99. package/dist/capabilities/ezkielyna.json +8 -8
  100. package/dist/capabilities/fastrouter.json +85 -85
  101. package/dist/capabilities/fireworks-ai.json +107 -44
  102. package/dist/capabilities/freemodel.json +23 -23
  103. package/dist/capabilities/friendli.json +9 -9
  104. package/dist/capabilities/frogbot.json +94 -94
  105. package/dist/capabilities/gisoo.json +16 -16
  106. package/dist/capabilities/gmicloud.json +17 -17
  107. package/dist/capabilities/google.json +57 -57
  108. package/dist/capabilities/graphn.json +10 -10
  109. package/dist/capabilities/greenpt.json +36 -36
  110. package/dist/capabilities/groq.json +2 -2
  111. package/dist/capabilities/helicone.json +68 -68
  112. package/dist/capabilities/hopper.json +2 -2
  113. package/dist/capabilities/hostinger-router.json +12 -12
  114. package/dist/capabilities/hpc-ai.json +13 -13
  115. package/dist/capabilities/huawei-maas.json +17 -17
  116. package/dist/capabilities/hubris.json +30 -30
  117. package/dist/capabilities/huggingface.json +193 -37
  118. package/dist/capabilities/hyper.json +23 -23
  119. package/dist/capabilities/impossibl.json +140 -140
  120. package/dist/capabilities/inception.json +2 -2
  121. package/dist/capabilities/inceptron.json +4 -4
  122. package/dist/capabilities/inco.json +3 -3
  123. package/dist/capabilities/infer.json +15 -15
  124. package/dist/capabilities/inferall.json +10 -10
  125. package/dist/capabilities/inference-coop.json +9 -9
  126. package/dist/capabilities/inferenceapis.json +9 -9
  127. package/dist/capabilities/inferris.json +3 -3
  128. package/dist/capabilities/infersia.json +2 -2
  129. package/dist/capabilities/inferx.json +3 -3
  130. package/dist/capabilities/infomaniak.json +4 -4
  131. package/dist/capabilities/io-net.json +2 -2
  132. package/dist/capabilities/isoquant.json +4 -4
  133. package/dist/capabilities/iteracompute.json +60 -60
  134. package/dist/capabilities/jad-ai.json +3 -3
  135. package/dist/capabilities/jalapeno.json +12 -12
  136. package/dist/capabilities/jiekou.json +63 -63
  137. package/dist/capabilities/jzstoken.json +50 -50
  138. package/dist/capabilities/keln.json +14 -21
  139. package/dist/capabilities/kenari.json +123 -120
  140. package/dist/capabilities/kilo.json +622 -647
  141. package/dist/capabilities/kimi-code-plan-cn.json +5 -5
  142. package/dist/capabilities/kimi-code-plan-global.json +5 -5
  143. package/dist/capabilities/kitani.json +6 -6
  144. package/dist/capabilities/klavo.json +18 -18
  145. package/dist/capabilities/korouter.json +29 -29
  146. package/dist/capabilities/kunavo.json +10 -10
  147. package/dist/capabilities/liquid.json +11 -11
  148. package/dist/capabilities/lithosai.json +2 -2
  149. package/dist/capabilities/llmgateway-providers.json +932 -905
  150. package/dist/capabilities/llmgateway.json +336 -336
  151. package/dist/capabilities/llmtr.json +22 -22
  152. package/dist/capabilities/logits.json +2 -2
  153. package/dist/capabilities/longcat.json +2 -7
  154. package/dist/capabilities/lowrouter.json +54 -54
  155. package/dist/capabilities/lyceum.json +12 -12
  156. package/dist/capabilities/melious.json +13 -13
  157. package/dist/capabilities/merge-gateway.json +260 -260
  158. package/dist/capabilities/meta.json +7 -7
  159. package/dist/capabilities/mistral.json +20 -20
  160. package/dist/capabilities/mixlayer.json +4 -4
  161. package/dist/capabilities/modal.json +10 -10
  162. package/dist/capabilities/model-oracle-ai.json +25 -25
  163. package/dist/capabilities/modelis.json +20 -20
  164. package/dist/capabilities/modular.json +6 -6
  165. package/dist/capabilities/moneo.json +16 -16
  166. package/dist/capabilities/moonshotai-cn.json +7 -7
  167. package/dist/capabilities/moonshotai.json +7 -7
  168. package/dist/capabilities/morph.json +11 -11
  169. package/dist/capabilities/munito-eu.json +6 -6
  170. package/dist/capabilities/munito.json +6 -6
  171. package/dist/capabilities/nan.json +27 -27
  172. package/dist/capabilities/nano-gpt.json +578 -578
  173. package/dist/capabilities/nearai.json +84 -84
  174. package/dist/capabilities/nebius.json +37 -28
  175. package/dist/capabilities/neon.json +126 -126
  176. package/dist/capabilities/neuralwatt.json +41 -41
  177. package/dist/capabilities/nokeep.json +4 -4
  178. package/dist/capabilities/novita-ai.json +154 -154
  179. package/dist/capabilities/nvidia.json +35 -35
  180. package/dist/capabilities/oathbreaker.json +2 -2
  181. package/dist/capabilities/obscurify.json +32 -32
  182. package/dist/capabilities/oci.json +7 -7
  183. package/dist/capabilities/ofox.json +357 -357
  184. package/dist/capabilities/ollama-cloud.json +56 -56
  185. package/dist/capabilities/openai.json +51 -51
  186. package/dist/capabilities/opencode-go.json +85 -84
  187. package/dist/capabilities/openrouter.json +542 -567
  188. package/dist/capabilities/opper.json +30 -24
  189. package/dist/capabilities/orcarouter.json +236 -236
  190. package/dist/capabilities/outerlabs.json +32 -32
  191. package/dist/capabilities/ovhcloud.json +7 -7
  192. package/dist/capabilities/pareto.json +6 -6
  193. package/dist/capabilities/pendra.json +4 -4
  194. package/dist/capabilities/perplexity-agent.json +61 -61
  195. package/dist/capabilities/phala.json +34 -34
  196. package/dist/capabilities/pioneer.json +30 -30
  197. package/dist/capabilities/poe.json +136 -136
  198. package/dist/capabilities/powerspring.json +13 -13
  199. package/dist/capabilities/primalabs.json +10 -10
  200. package/dist/capabilities/prime.json +124 -107
  201. package/dist/capabilities/privatemode-ai.json +14 -14
  202. package/dist/capabilities/proxystacks.json +6 -6
  203. package/dist/capabilities/qiniu-ai.json +16 -16
  204. package/dist/capabilities/refuseless.json +6 -6
  205. package/dist/capabilities/regolo-ai.json +6 -6
  206. package/dist/capabilities/requesty.json +172 -172
  207. package/dist/capabilities/ruapi.json +17 -17
  208. package/dist/capabilities/runcrate.json +5 -5
  209. package/dist/capabilities/runinfra.json +13 -13
  210. package/dist/capabilities/sakana.json +6 -6
  211. package/dist/capabilities/sambanova.json +9 -9
  212. package/dist/capabilities/sandbase.json +27 -27
  213. package/dist/capabilities/sarvam.json +12 -12
  214. package/dist/capabilities/scaleway.json +14 -14
  215. package/dist/capabilities/scnet-token-plan.json +9 -9
  216. package/dist/capabilities/scx-ai.json +26 -26
  217. package/dist/capabilities/sensenova.json +12 -12
  218. package/dist/capabilities/siliconflow-cn.json +49 -49
  219. package/dist/capabilities/siliconflow.json +46 -46
  220. package/dist/capabilities/snowflake-cortex.json +20 -20
  221. package/dist/capabilities/sokkan.json +7 -7
  222. package/dist/capabilities/sparrowcodes.json +25 -25
  223. package/dist/capabilities/standardcompute.json +102 -102
  224. package/dist/capabilities/steadyrouter.json +40 -40
  225. package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
  226. package/dist/capabilities/stepfun-ai.json +15 -8
  227. package/dist/capabilities/stepfun-step-plan.json +15 -8
  228. package/dist/capabilities/stepfun.json +15 -8
  229. package/dist/capabilities/stepping-stone.json +16 -16
  230. package/dist/capabilities/synthetic.json +13 -13
  231. package/dist/capabilities/synthorai.json +19 -19
  232. package/dist/capabilities/teamorouter.json +24 -24
  233. package/dist/capabilities/teapot-router.json +13 -13
  234. package/dist/capabilities/tencent-coding-plan.json +1 -23
  235. package/dist/capabilities/tencent-token-plan.json +60 -23
  236. package/dist/capabilities/tencent-tokenhub.json +182 -7
  237. package/dist/capabilities/tensorx.json +50 -50
  238. package/dist/capabilities/tenstorrent.json +6 -6
  239. package/dist/capabilities/the-grid-ai.json +28 -28
  240. package/dist/capabilities/thinkingmachines.json +72 -55
  241. package/dist/capabilities/tinfoil.json +13 -13
  242. package/dist/capabilities/toapis.json +2 -2
  243. package/dist/capabilities/togetherai.json +54 -83
  244. package/dist/capabilities/tokengo.json +25 -25
  245. package/dist/capabilities/tokenify.json +9 -9
  246. package/dist/capabilities/trustedrouter.json +4 -4
  247. package/dist/capabilities/trustedtokens.json +17 -17
  248. package/dist/capabilities/umans-ai-coding-plan.json +13 -13
  249. package/dist/capabilities/umans-ai.json +10 -10
  250. package/dist/capabilities/unrestricted.json +6 -6
  251. package/dist/capabilities/uplinkswitch.json +21 -21
  252. package/dist/capabilities/upstage.json +4 -4
  253. package/dist/capabilities/vancine.json +23 -23
  254. package/dist/capabilities/vercel.json +540 -527
  255. package/dist/capabilities/vivgrid.json +80 -80
  256. package/dist/capabilities/volcengine-coding-plan.json +24 -54
  257. package/dist/capabilities/volcengine.json +55 -60
  258. package/dist/capabilities/vultr.json +24 -24
  259. package/dist/capabilities/wafer.ai.json +19 -19
  260. package/dist/capabilities/wallaby.json +5 -5
  261. package/dist/capabilities/wally.json +11 -11
  262. package/dist/capabilities/wandb.json +21 -21
  263. package/dist/capabilities/watt.json +24 -24
  264. package/dist/capabilities/xai.json +7 -7
  265. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -12
  266. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -12
  267. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -12
  268. package/dist/capabilities/xiaomi.json +3 -25
  269. package/dist/capabilities/xpersona.json +13 -13
  270. package/dist/capabilities/xxapi.json +31 -31
  271. package/dist/capabilities/zai-coding-plan.json +18 -18
  272. package/dist/capabilities/zai.json +49 -26
  273. package/dist/capabilities/zenifra.json +26 -26
  274. package/dist/capabilities/zenmux.json +205 -205
  275. package/dist/capabilities/zerogpu.json +11 -11
  276. package/dist/capabilities/zhipuai-coding-plan.json +6 -6
  277. package/dist/capabilities/zhipuai.json +39 -24
  278. package/dist/capabilities/zro.json +6 -6
  279. package/dist/channels/index.cjs +2 -2
  280. package/dist/channels/index.js +2 -2
  281. package/dist/{channels-Dx4jiXeK.js → channels-Cz1y3W6u.js} +1 -1
  282. package/dist/{channels-q6qnuRNV.cjs → channels-DQg4v_gm.cjs} +1 -1
  283. package/dist/coding-agent/index.cjs +2 -2
  284. package/dist/coding-agent/index.js +2 -2
  285. package/dist/datasets/dataset.d.ts +13 -6
  286. package/dist/datasets/experiment/durable.d.ts +16 -0
  287. package/dist/datasets/experiment/index.d.ts +2 -1
  288. package/dist/datasets/experiment/item.d.ts +26 -4
  289. package/dist/datasets/experiment/retries.d.ts +18 -0
  290. package/dist/datasets/experiment/types.d.ts +18 -0
  291. package/dist/datasets/experiment/workflow-id.d.ts +7 -0
  292. package/dist/datasets/experiment/workflow.d.ts +74 -0
  293. package/dist/datasets/index.cjs +3 -2
  294. package/dist/datasets/index.d.ts +2 -1
  295. package/dist/datasets/index.js +3 -3
  296. package/dist/docs/SKILL.md +4 -3
  297. package/dist/docs/assets/SOURCE_MAP.json +928 -903
  298. package/dist/docs/references/docs-deployment-workers.md +1 -1
  299. package/dist/docs/references/docs-evals-experiments.md +29 -1
  300. package/dist/docs/references/docs-harness-background-tasks.md +4 -1
  301. package/dist/docs/references/docs-harness-durable-agents.md +9 -5
  302. package/dist/docs/references/docs-knowledge-agents-and-tools.md +1 -0
  303. package/dist/docs/references/docs-knowledge-importers.md +195 -0
  304. package/dist/docs/references/docs-knowledge-load-your-content.md +2 -2
  305. package/dist/docs/references/docs-knowledge-overview.md +1 -1
  306. package/dist/docs/references/docs-mastra-platform-observability-overview.md +1 -1
  307. package/dist/docs/references/docs-sandbox-filesystem.md +1 -1
  308. package/dist/docs/references/docs-server-pubsub.md +51 -8
  309. package/dist/docs/references/docs-signals-running-across-processes.md +2 -0
  310. package/dist/docs/references/docs-signals-thread-streams.md +1 -1
  311. package/dist/docs/references/docs-studio-auth.md +54 -7
  312. package/dist/docs/references/docs-workflows-overview.md +1 -1
  313. package/dist/docs/references/docs-workflows-scheduled-workflows.md +1 -1
  314. package/dist/docs/references/integrations-auth-clerk.md +48 -4
  315. package/dist/docs/references/integrations-channels-slack.md +4 -2
  316. package/dist/docs/references/integrations.md +6 -0
  317. package/dist/docs/references/reference-agents-agent.md +3 -1
  318. package/dist/docs/references/reference-agents-channels.md +116 -27
  319. package/dist/docs/references/reference-agents-durable-agent.md +12 -4
  320. package/dist/docs/references/reference-auth-clerk.md +21 -1
  321. package/dist/docs/references/reference-datasets-runExperimentItem.md +13 -1
  322. package/dist/docs/references/reference-datasets-startExperimentAsync.md +3 -1
  323. package/dist/docs/references/reference-editor-mastra-editor.md +3 -1
  324. package/dist/docs/references/reference-knowledge-knowledge-class.md +13 -6
  325. package/dist/docs/references/reference-knowledge-knowledge-tools.md +43 -20
  326. package/dist/docs/references/reference-memory-observational-memory.md +2 -2
  327. package/dist/docs/references/reference-processors-moderation-processor.md +2 -2
  328. package/dist/docs/references/reference-pubsub-base.md +5 -1
  329. package/dist/docs/references/reference-pubsub-event-emitter.md +2 -0
  330. package/dist/docs/references/reference-pubsub-redis-streams.md +1 -1
  331. package/dist/docs/references/reference-pubsub-unix-socket-pubsub.md +2 -0
  332. package/dist/docs/references/reference-streaming-ChunkType.md +3 -3
  333. package/dist/docs/references/reference-workers-overview.md +1 -1
  334. package/dist/docs/references/reference-workflows-run-methods-start.md +23 -0
  335. package/dist/docs/references/reference-workflows-run-methods-timeTravel.md +4 -0
  336. package/dist/docs/references/reference-workflows-run.md +1 -1
  337. package/dist/docs/references/reference-workspace-local-sandbox.md +2 -0
  338. package/dist/error/index.cjs +1 -1
  339. package/dist/error/index.js +1 -1
  340. package/dist/{error-C9d_24w-.js → error-BLwEXqOK.js} +2 -2
  341. package/dist/{error-BRQf2ku0.cjs → error-BdEvO8za.cjs} +2 -2
  342. package/dist/evals/index.cjs +1 -1
  343. package/dist/evals/index.js +1 -1
  344. package/dist/evals/scoreTraces/index.cjs +1 -1
  345. package/dist/evals/scoreTraces/index.js +1 -1
  346. package/dist/events/caching-pubsub.d.ts +1 -0
  347. package/dist/events/event-emitter/index.d.ts +12 -5
  348. package/dist/events/index.cjs +15 -1
  349. package/dist/events/index.js +15 -1
  350. package/dist/events/pubsub.d.ts +29 -0
  351. package/dist/events/reach.d.ts +11 -0
  352. package/dist/events/unix-socket-pubsub.d.ts +14 -0
  353. package/dist/features/index.cjs +1 -0
  354. package/dist/features/index.js +1 -0
  355. package/dist/{filesystem-B5X-5G0x.js → filesystem-B8ad6kAW.js} +1 -1
  356. package/dist/{filesystem-BDSpwBke.cjs → filesystem-BB5YWXH-.cjs} +1 -1
  357. package/dist/{filesystem-DzM9pcQ8.js → filesystem-BDHUxbHn.js} +1 -1
  358. package/dist/{filesystem-B0AZrbj8.cjs → filesystem-BP5yz5LG.cjs} +1 -1
  359. package/dist/{filesystem-BsdkC311.js → filesystem-B_afSgYk.js} +1 -1
  360. package/dist/{filesystem-C-cyJfi1.cjs → filesystem-BaOJOc-V.cjs} +1 -1
  361. package/dist/{filesystem-B3s0WRud.js → filesystem-BhYgU8qg.js} +1 -1
  362. package/dist/{filesystem-DzfqVTO_.js → filesystem-CLBVmR5j.js} +1 -1
  363. package/dist/{filesystem-CEbD_77-.cjs → filesystem-Cgxc2a_-.cjs} +1 -1
  364. package/dist/{filesystem-Cv79mHRk.js → filesystem-ClBOBoDc.js} +1 -1
  365. package/dist/{filesystem-DsCQiBl2.cjs → filesystem-DVVecqZt.cjs} +1 -1
  366. package/dist/{filesystem-CUAgLugE.cjs → filesystem-Fpsu7e24.cjs} +1 -1
  367. package/dist/{filesystem-versioned-Bijb_p9l.js → filesystem-versioned-BL1ojJLo.js} +1 -1
  368. package/dist/{filesystem-versioned-DZGyPbNC.cjs → filesystem-versioned-BavRtYWJ.cjs} +1 -1
  369. package/dist/harness/index.cjs +1 -1
  370. package/dist/harness/index.js +1 -1
  371. package/dist/index.cjs +1 -1
  372. package/dist/index.js +1 -1
  373. package/dist/knowledge/config.d.ts +10 -0
  374. package/dist/knowledge/host-writes.d.ts +10 -0
  375. package/dist/knowledge/importers/conformance.d.ts +25 -0
  376. package/dist/knowledge/importers/define.d.ts +204 -0
  377. package/dist/knowledge/importers/host.d.ts +143 -0
  378. package/dist/knowledge/importers/index.d.ts +12 -0
  379. package/dist/knowledge/importers/local-host.d.ts +106 -0
  380. package/dist/knowledge/importers/manifest.d.ts +25 -0
  381. package/dist/knowledge/importers/runner.d.ts +61 -0
  382. package/dist/knowledge/importers/sink.d.ts +105 -0
  383. package/dist/knowledge/importers/types.d.ts +144 -0
  384. package/dist/knowledge/index.cjs +2715 -8
  385. package/dist/knowledge/index.d.ts +54 -4
  386. package/dist/knowledge/index.js +2692 -9
  387. package/dist/knowledge/instructions.d.ts +1 -1
  388. package/dist/knowledge/links.d.ts +8 -0
  389. package/dist/knowledge/pinned-state-processor.d.ts +5 -0
  390. package/dist/knowledge/pinned.d.ts +4 -1
  391. package/dist/knowledge/scope-runtime.d.ts +10 -0
  392. package/dist/llm/index.cjs +3 -3
  393. package/dist/llm/index.js +3 -3
  394. package/dist/llm/model/provider-types.generated.d.ts +7812 -7831
  395. package/dist/llm/model/shared.types.d.ts +31 -0
  396. package/dist/{llm-CsQuqKPc.cjs → llm-8Av3mSjD.cjs} +2 -2
  397. package/dist/{llm-DnXK3Pmw.js → llm-B5A5cwJr.js} +2 -2
  398. package/dist/loop/index.cjs +2 -2
  399. package/dist/loop/index.js +2 -2
  400. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +2 -2
  401. package/dist/{manager-BsghM-UL.js → manager-DfWQCJUK.js} +460 -94
  402. package/dist/{manager-DwFnIrI6.cjs → manager-sv35JY-z.cjs} +476 -92
  403. package/dist/mastra/index.cjs +1 -1
  404. package/dist/mastra/index.d.ts +13 -0
  405. package/dist/mastra/index.js +1 -1
  406. package/dist/mastra/resolve-agent.d.ts +3 -1
  407. package/dist/{mastra-B8i1UDZs.js → mastra-CigBrT7X.js} +32 -23
  408. package/dist/{mastra-Cn5NC6Es.cjs → mastra-D4hvfuxX.cjs} +34 -25
  409. package/dist/memory/index.cjs +3 -3
  410. package/dist/memory/index.js +3 -3
  411. package/dist/{message-list-DPXPXvin.cjs → message-list-Cj0Sq_JP.cjs} +63 -8
  412. package/dist/{message-list-DEuRl82K.js → message-list-KRbg-TnI.js} +63 -8
  413. package/dist/{model-CNPfry_X.cjs → model-BK93CMtl.cjs} +1 -1
  414. package/dist/{model-CsOcWMUt.js → model-CYtXw861.js} +1 -1
  415. package/dist/{netlify-C-83Fxus.cjs → netlify-BAnn3ouY.cjs} +1 -1
  416. package/dist/{netlify-C-OpNSGp.js → netlify-CuI1ZrwR.js} +1 -1
  417. package/dist/notifications/index.cjs +1 -1
  418. package/dist/notifications/index.js +1 -1
  419. package/dist/{output-helpers-JL-HeCbT.cjs → output-helpers-1Zu4Vt9C.cjs} +68 -25
  420. package/dist/{output-helpers-D4II19No.js → output-helpers-CedRCE17.js} +69 -26
  421. package/dist/processor-provider/index.cjs +1 -1
  422. package/dist/processor-provider/index.js +1 -1
  423. package/dist/processors/abort-signal-scope.d.ts +6 -0
  424. package/dist/processors/index.cjs +2 -2
  425. package/dist/processors/index.js +2 -2
  426. package/dist/{provider-registry-9O-H9osy.cjs → provider-registry-BwuI_IpT.cjs} +21690 -21811
  427. package/dist/{provider-registry-RZ8EgSe8.js → provider-registry-CmQLzLF_.js} +21690 -21811
  428. package/dist/provider-registry.json +22113 -22215
  429. package/dist/{registry-generator-e8sltJls.js → registry-generator-C17V4WfG.js} +1 -1
  430. package/dist/{registry-generator-DxCX-FiO.cjs → registry-generator-C_0ae7Ce.cjs} +1 -1
  431. package/dist/{rehydrate-B-wrAN7C.cjs → rehydrate-CDQ4dOYj.cjs} +2 -2
  432. package/dist/{rehydrate-D3fPgJwp.js → rehydrate-PnaVawGX.js} +2 -2
  433. package/dist/relevance/index.cjs +2 -2
  434. package/dist/relevance/index.js +2 -2
  435. package/dist/{run-registry-5_LQBGn_.cjs → run-registry-BmckDVBk.cjs} +1698 -497
  436. package/dist/{run-registry-DC03XLeZ.js → run-registry-BwEcwYlU.js} +1614 -467
  437. package/dist/{source-DDwx-87N.cjs → source-BVOi8Xhp.cjs} +1 -1
  438. package/dist/{source-Did_2XQc.js → source-fNa6u1kH.js} +1 -1
  439. package/dist/storage/domains/agents/index.cjs +1 -1
  440. package/dist/storage/domains/agents/index.js +1 -1
  441. package/dist/storage/domains/knowledge/base.d.ts +72 -0
  442. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +146 -0
  443. package/dist/storage/domains/knowledge/importers.d.ts +287 -0
  444. package/dist/storage/domains/knowledge/index.d.ts +1 -0
  445. package/dist/storage/domains/knowledge/inmemory.d.ts +12 -0
  446. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +12 -1
  447. package/dist/storage/domains/knowledge/pages.d.ts +25 -7
  448. package/dist/storage/domains/mcp-clients/index.cjs +1 -1
  449. package/dist/storage/domains/mcp-clients/index.js +1 -1
  450. package/dist/storage/domains/mcp-servers/index.cjs +1 -1
  451. package/dist/storage/domains/mcp-servers/index.js +1 -1
  452. package/dist/storage/domains/prompt-blocks/index.cjs +1 -1
  453. package/dist/storage/domains/prompt-blocks/index.js +1 -1
  454. package/dist/storage/domains/scorer-definitions/index.cjs +1 -1
  455. package/dist/storage/domains/scorer-definitions/index.js +1 -1
  456. package/dist/storage/domains/skills/index.cjs +1 -1
  457. package/dist/storage/domains/skills/index.js +1 -1
  458. package/dist/storage/domains/workspaces/index.cjs +1 -1
  459. package/dist/storage/domains/workspaces/index.js +1 -1
  460. package/dist/storage/index.cjs +15 -10
  461. package/dist/storage/index.js +11 -11
  462. package/dist/stream/base/output.d.ts +59 -15
  463. package/dist/stream/index.cjs +2 -2
  464. package/dist/stream/index.js +2 -2
  465. package/dist/stream/types.d.ts +24 -2
  466. package/dist/{stream-4aNIw_TQ.cjs → stream-0kdqBOOn.cjs} +64 -9
  467. package/dist/{stream-CJUm6EAH.js → stream-D1y9GzoD.js} +29 -10
  468. package/dist/test-utils/llm-mock.cjs +1 -1
  469. package/dist/test-utils/llm-mock.js +1 -1
  470. package/dist/tool-loop-agent/index.cjs +1 -1
  471. package/dist/tool-loop-agent/index.js +1 -1
  472. package/dist/{tool-loop-agent-FEEwHfmg.js → tool-loop-agent-BdjWGVIb.js} +4 -4
  473. package/dist/{tool-loop-agent-Dn0QCB9n.cjs → tool-loop-agent-kWaZAT6Q.cjs} +4 -4
  474. package/dist/tools/types.d.ts +27 -1
  475. package/dist/{utils-DY01hxVd.cjs → utils-BKUCaZ12.cjs} +1 -1
  476. package/dist/{utils-Bd_y1_a-.js → utils-GHY3hmLx.js} +1 -1
  477. package/dist/utils.cjs +1 -1
  478. package/dist/utils.js +1 -1
  479. package/dist/{validate-CX0yQo_q.js → validate-CB-q-R2F.js} +1 -1
  480. package/dist/{validate-CuB_1Zd3.cjs → validate-De92squ7.cjs} +1 -1
  481. package/dist/vector/index.cjs +2 -2
  482. package/dist/vector/index.js +2 -2
  483. package/dist/worker/index.cjs +1 -1
  484. package/dist/worker/index.js +1 -1
  485. package/dist/{worker-CbaSmip-.cjs → worker-BbWPQuPR.cjs} +2 -2
  486. package/dist/{worker-B80xkcKG.js → worker-C3u_xzY2.js} +2 -2
  487. package/dist/{worker-GsGIxPMa.cjs → worker-CAKvQj9_.cjs} +2 -2
  488. package/dist/{worker-DSEfMPmq.js → worker-Kwm8EKcj.js} +2 -2
  489. package/dist/{workflow-CnBPXTpv.cjs → workflow-CSjXeNcR.cjs} +4 -4
  490. package/dist/{workflow-CZHY_C85.js → workflow-CVmI1Sw-.js} +4 -4
  491. package/dist/workflows/builder/index.cjs +1 -1
  492. package/dist/workflows/builder/index.js +1 -1
  493. package/dist/workflows/evented/index.cjs +1 -1
  494. package/dist/workflows/evented/index.js +1 -1
  495. package/dist/workflows/evented/setup-warning.d.ts +18 -0
  496. package/dist/workflows/evented/workflow-event-processor/run-status.d.ts +37 -0
  497. package/dist/workflows/evented/workflow.d.ts +10 -0
  498. package/dist/workflows/index.cjs +4 -4
  499. package/dist/workflows/index.js +4 -4
  500. package/dist/workflows/workflow.d.ts +6 -1
  501. package/dist/workspace/filesystem/filesystem.d.ts +5 -0
  502. package/dist/workspace/index.cjs +1 -1
  503. package/dist/workspace/index.js +1 -1
  504. package/dist/workspace/sandbox/local-sandbox.d.ts +16 -7
  505. package/dist/workspace/sandbox/native-sandbox/types.d.ts +11 -1
  506. package/dist/{workspace-D7TIleIt.js → workspace-DY2Nxiyi.js} +235 -34
  507. package/dist/{workspace-D2drutNg.cjs → workspace-X2RHJZU9.cjs} +235 -34
  508. package/package.json +7 -7
  509. package/src/llm/model/provider-types.generated.d.ts +7812 -7831
@@ -0,0 +1,37 @@
1
+ import type { WorkflowRunStatus } from '../../types.js';
2
+ /** The statuses of a run that has not ended yet. */
3
+ export declare const UNENDED_RUN_STATUSES: WorkflowRunStatus[];
4
+ /** Whether a run stored with `status` has ended. */
5
+ export declare function isEndedRunStatus(status: string | undefined): boolean;
6
+ type EndedRunStatus = 'success' | 'failed' | 'canceled' | 'tripwire';
7
+ /** Whether the stored run `run` has ended. */
8
+ export declare function hasRunEnded<T extends {
9
+ status?: string;
10
+ }>(run: T | null | undefined): run is T & {
11
+ status: EndedRunStatus;
12
+ };
13
+ /** Whether `executionPath` points past the last entry of `stepGraph`: a step run there ends the run. */
14
+ export declare function isPastLastEntry(stepGraph: readonly unknown[], executionPath: number[] | undefined): boolean;
15
+ /**
16
+ * Whether a step event is the one that ended the stored run `run`, which a worker still handles
17
+ * when the run has ended. Only a successful run has one: its worker stores the end before
18
+ * publishing it and may stop in between, and handling the event again publishes the end. The
19
+ * stored active path names it: the step end the run ended at, or the step run past the last entry.
20
+ * A failed run's end is stored by its own `workflow.fail`, which a redelivery of that event
21
+ * finishes.
22
+ *
23
+ * This can't tell an end that was stored and not published from one that was already handled, so
24
+ * a late copy of the event publishes the end again (and, for a nested run, hands it to the parent
25
+ * again).
26
+ */
27
+ export declare function isRunEndingEvent(type: string, executionPath: number[] | undefined, run: {
28
+ status?: string;
29
+ activePaths?: number[];
30
+ }, stepGraph: readonly unknown[] | undefined): boolean;
31
+ /**
32
+ * Whether two execution paths name the same position in the step graph. A missing path matches
33
+ * only another missing path: a run stored without active paths was ended by an event without one.
34
+ */
35
+ export declare function samePath(a: number[] | undefined, b: number[] | undefined): boolean;
36
+ export {};
37
+ //# sourceMappingURL=run-status.d.ts.map
@@ -98,6 +98,16 @@ export declare function createStep<TProcessorId extends string, TInput extends I
98
98
  * This is a copy of first one, KEEP THIS IN SYNC!
99
99
  */
100
100
  export declare function createStep<TStepId extends string, TStateSchema extends PublicSchema<any> | undefined, TInputSchema extends PublicSchema<any>, TOutputSchema extends PublicSchema<any>, TResumeSchema extends PublicSchema<any> | undefined = undefined, TSuspendSchema extends PublicSchema<any> | undefined = undefined>(params: StepParams<TStepId, TStateSchema, TInputSchema, TOutputSchema, TResumeSchema, TSuspendSchema>): Step<TStepId, TStateSchema extends PublicSchema<any> ? InferPublicSchema<TStateSchema> : unknown, InferPublicSchema<TInputSchema>, InferPublicSchema<TOutputSchema>, TResumeSchema extends PublicSchema<any> ? InferPublicSchema<TResumeSchema> : unknown, TSuspendSchema extends PublicSchema<any> ? InferPublicSchema<TSuspendSchema> : unknown, DefaultEngineType>;
101
+ /**
102
+ * Builds a workflow on the evented execution engine: each step is an event on
103
+ * the Mastra host's pubsub, so any worker can run the next one.
104
+ *
105
+ * In one process it runs on any pubsub, including the default one. Running it
106
+ * on several processes needs a pubsub that redelivers unacknowledged events and
107
+ * a workflows store with step guards.
108
+ *
109
+ * @see https://mastra.ai/docs/server/pubsub#evented-workflows-and-agents
110
+ */
101
111
  export declare function createWorkflow<TWorkflowId extends string = string, TInputSchema extends PublicSchema<any> = PublicSchema<any>, TOutputSchema extends PublicSchema<any> = PublicSchema<any>, TStateSchema extends PublicSchema<any> | undefined = undefined, TSteps extends Step<string, any, any, any, any, any, EventedEngineType>[] = Step<string, any, any, any, any, any, EventedEngineType>[], TRequestContextSchema extends PublicSchema<any> | undefined = undefined, TStorageVersion extends 1 | 2 = 1>(params: CreateWorkflowParams<TWorkflowId, TStateSchema, TInputSchema, TOutputSchema, TSteps, TRequestContextSchema, TStorageVersion>): EventedWorkflow<EventedEngineType, TSteps, TWorkflowId, InferSchemaOutput<TStateSchema>, InferPublicSchema<TInputSchema>, InferPublicSchema<TOutputSchema>, InferPublicSchema<TInputSchema>, TStorageVersion>;
102
112
  export declare class EventedWorkflow<TEngineType = EventedEngineType, TSteps extends Step<string, any, any>[] = Step<string, any, any>[], TWorkflowId extends string = string, TState = unknown, TInput = unknown, TOutput = unknown, TPrevSchema = TInput, TStorageVersion extends 1 | 2 = any> extends Workflow<TEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrevSchema, unknown, TStorageVersion> {
103
113
  constructor(params: WorkflowConfig<TWorkflowId, TState, TInput, TOutput, TSteps, unknown, TStorageVersion>);
@@ -1,11 +1,11 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_run_registry = require("../run-registry-5_LQBGn_.cjs");
3
- const require_stream = require("../stream-4aNIw_TQ.cjs");
2
+ const require_run_registry = require("../run-registry-BmckDVBk.cjs");
3
+ const require_stream = require("../stream-0kdqBOOn.cjs");
4
4
  const require_predicate_index = require("../predicate/index.cjs");
5
5
  const require_schedules = require("../schedules-BZS8McF7.cjs");
6
6
  const require_scheduler = require("../scheduler-D00X03jQ.cjs");
7
- const require_validate = require("../validate-CuB_1Zd3.cjs");
8
- const require_rehydrate = require("../rehydrate-B-wrAN7C.cjs");
7
+ const require_validate = require("../validate-De92squ7.cjs");
8
+ const require_rehydrate = require("../rehydrate-CDQ4dOYj.cjs");
9
9
  // src/workflows/state-reader.ts
10
10
  const getStep = (state, stepId) => state.steps?.[stepId];
11
11
  const getFirstStepResult = (step) => {
@@ -1,10 +1,10 @@
1
- import { $c as validateStepInput, Ac as RESUME_SNAPSHOT_POLL_INTERVAL_MS, Bc as defineStateAccessors, Dc as createStepFromAgent, Ec as createMappingStep, Fc as cleanStepResult, Gc as hydrateSerializedStepErrors, Hc as getResumeLabelsByStepId, Ic as createDeprecationProxy, Jc as omitPriorCompletionFields, Kc as isEntryFinished, Lc as createRestartExecutionParams, Mc as abortableSleep, Nc as applyStateDelta, Oc as createStepFromClassifier, Pc as assertTimeTravelGraphMatchesSnapshot, Qc as setLongTimeout, Rc as createTimeTravelExecutionParams, Sc as ExecutionEngine, Ss as createWorkflow, Uc as getSingleStepEntryId, Vc as getRestartStartIndex, Wc as getStepIds, Xc as resolveForeachConcurrency, Yc as omitPriorSuspensionFields, Zc as runCountDeprecationMessage, ac as createStep, al as getEntryId, bs as cloneWorkflow, cc as predicateToCondition, el as validateStepRequestContext, ic as cloneStep, il as waitForSuspendedSnapshot, jc as RESUME_SNAPSHOT_WAIT_STATUSES, js as computeScheduleDefinitionHash, kc as createStepFromTool, lc as evaluatePredicate, ll as workflowTermination, nc as Run, nl as validateStepStateData, oc as isProcessor, ol as getEntryWorkflow, qc as isSingleStepEntry, rc as Workflow, rl as validateStepSuspendData, sc as mapVariable, tl as validateStepResumeData, vc as DefaultExecutionEngine, xs as createEventedWorkflow, zc as defineLazyWriter } from "../run-registry-DC03XLeZ.js";
2
- import { St as getStepResultAsync, xt as getStepResult } from "../stream-CJUm6EAH.js";
1
+ import { $c as hydrateSerializedStepErrors, Ac as ExecutionEngine, As as createWorkflow, Bc as abortableSleep, Ec as DefaultExecutionEngine, Fc as createStepFromAgent, Gc as createRestartExecutionParams, Hc as assertTimeTravelGraphMatchesSnapshot, Ic as createStepFromClassifier, Jc as defineStateAccessors, Kc as createTimeTravelExecutionParams, Lc as createStepFromTool, Os as cloneWorkflow, Pc as createMappingStep, Qc as getStepIds, Rc as RESUME_SNAPSHOT_POLL_INTERVAL_MS, Uc as cleanStepResult, Vc as applyStateDelta, Wc as createDeprecationProxy, Xc as getResumeLabelsByStepId, Yc as getRestartStartIndex, Zc as getSingleStepEntryId, _c as evaluatePredicate, _l as workflowTermination, al as runCountDeprecationMessage, cl as validateStepRequestContext, dc as Workflow, dl as validateStepSuspendData, el as isEntryFinished, fc as cloneStep, fl as waitForSuspendedSnapshot, gc as predicateToCondition, hc as mapVariable, il as resolveForeachConcurrency, ks as createEventedWorkflow, ll as validateStepResumeData, mc as isProcessor, ml as getEntryWorkflow, nl as omitPriorCompletionFields, ol as setLongTimeout, pc as createStep, pl as getEntryId, qc as defineLazyWriter, rl as omitPriorSuspensionFields, sl as validateStepInput, tl as isSingleStepEntry, uc as Run, ul as validateStepStateData, zc as RESUME_SNAPSHOT_WAIT_STATUSES, zs as computeScheduleDefinitionHash } from "../run-registry-BwEcwYlU.js";
2
+ import { Dt as getStepResult, Ot as getStepResultAsync } from "../stream-D1y9GzoD.js";
3
3
  import { derivePredicateLabel, predicateSchema } from "../predicate/index.js";
4
4
  import { _ as validateCron, h as computeNextFireAt } from "../schedules-DZfSx-7P.js";
5
5
  import { n as WorkflowScheduler, t as Scheduler } from "../scheduler-B-VZUvv_.js";
6
- import { a as jsonSchemaToZod, c as analyzeMapConfig, d as toJsonSchemaOrUndefined, f as validateWorkflowRefs, h as forEachSingleStepEntryWithPath, i as validateWorkflowSchemas, l as parseMapConfig, m as forEachSingleStepEntry, n as validateDynamicWorkflow, o as validateStorableJsonSchema, p as collectNestedWorkflowIds, r as validateWorkflowStructure, s as inferGraphSchemas, t as assertValidDynamicWorkflow, u as schemaCompatibility } from "../validate-CX0yQo_q.js";
7
- import { n as entryOptionFields, r as toStorableGraph, t as rehydrateWorkflow } from "../rehydrate-D3fPgJwp.js";
6
+ import { a as jsonSchemaToZod, c as analyzeMapConfig, d as toJsonSchemaOrUndefined, f as validateWorkflowRefs, h as forEachSingleStepEntryWithPath, i as validateWorkflowSchemas, l as parseMapConfig, m as forEachSingleStepEntry, n as validateDynamicWorkflow, o as validateStorableJsonSchema, p as collectNestedWorkflowIds, r as validateWorkflowStructure, s as inferGraphSchemas, t as assertValidDynamicWorkflow, u as schemaCompatibility } from "../validate-CB-q-R2F.js";
7
+ import { n as entryOptionFields, r as toStorableGraph, t as rehydrateWorkflow } from "../rehydrate-PnaVawGX.js";
8
8
  // src/workflows/state-reader.ts
9
9
  const getStep = (state, stepId) => state.steps?.[stepId];
10
10
  const getFirstStepResult = (step) => {
@@ -430,12 +430,17 @@ export declare class Workflow<TEngineType = DefaultEngineType, TSteps extends St
430
430
  protected takeNestedRun(): {
431
431
  /** The parent run's storage version, which a new nested run takes. */
432
432
  storageVersion: 1 | 2;
433
- /** Set when execute() starts the nested run rather than resuming or restarting it. */
433
+ /**
434
+ * Set when execute() may start the nested run: on a start, and on a restart, which starts it
435
+ * when it wasn't stored before. Unset on a resume.
436
+ */
434
437
  start?: {
435
438
  input: TInput;
436
439
  state: TState;
437
440
  inheritedState?: StateBase;
438
441
  };
442
+ /** Set by createRun() when it saved the run's first snapshot: the run wasn't stored before. */
443
+ inserted?: boolean;
439
444
  } | undefined;
440
445
  /**
441
446
  * Resolves the storage version a createRun() call uses, and reads the stored run that call
@@ -203,6 +203,11 @@ export interface WorkspaceFilesystem extends FilesystemLifecycle<FilesystemInfo>
203
203
  * When true, all write operations to this filesystem are blocked.
204
204
  * Read operations are still allowed.
205
205
  *
206
+ * Applies to the filesystem API and file tools. When the filesystem is
207
+ * mounted into a `LocalSandbox` with native isolation, the mount is also
208
+ * made read-only for commands; without isolation, commands are not
209
+ * restricted.
210
+ *
206
211
  * @default false
207
212
  */
208
213
  readonly readOnly?: boolean;
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_workspace = require("../workspace-D2drutNg.cjs");
2
+ const require_workspace = require("../workspace-X2RHJZU9.cjs");
3
3
  const require_errors = require("../errors-D5kMB1FQ.cjs");
4
4
  const require_workspace_skills = require("../workspace-skills-BcquhPDn.cjs");
5
5
  exports.CompositeFilesystem = require_workspace.CompositeFilesystem;
@@ -1,4 +1,4 @@
1
- import { $ as SandboxExecutionError, A as requireFilesystem, B as UnsupportedStdinCloseError, C as DEFAULT_TAIL_LINES, D as editFileTool, F as getRecommendedIsolation, G as validateSandboxFileMode, H as assertModesUnsupported, I as isIsolationAvailable, J as IsolationUnavailableError, K as MountManager, L as SandboxProcessManager, M as requireWorkspace, N as LocalSandbox, O as deleteFileTool, P as detectIsolation, Q as SandboxError, R as MastraSandbox, S as executeCommandTool, U as supportsComputer, V as MAX_SANDBOX_FILE_MODE, W as supportsNetworking, X as MountNotSupportedError, Y as MountError, Z as SandboxAbortError, _ as readFileTool, a as normalizeFactorySandboxSettings, at as LocalFilesystem, b as indexContentTool, c as formatSkillActivation, ct as callLifecycle, d as CompositeVersionedSkillSource, et as SandboxNotReadyError, f as VersionedSkillSource, g as searchTool, h as writeFileTool, i as isFactorySandbox, j as requireSandbox, k as applyPatchTool, l as collectSkillForPublish, lt as WORKSPACE_TOOLS, m as resolveToolConfig, n as FactorySandbox, nt as SandboxUnsupportedFeatureError, o as Workspace, ot as MastraFilesystem, p as createWorkspaceTools, q as FilesystemNotMountableError, r as describeFactorySandbox, s as createSkillTools, st as CompositeFilesystem, t as FACTORY_SANDBOX_BRAND, tt as SandboxTimeoutError, u as publishSkillFromSource, ut as WORKSPACE_TOOLS_PREFIX, v as mkdirTool, w as truncateOutput, x as fileStatTool, y as listFilesTool, z as ProcessHandle } from "../workspace-D7TIleIt.js";
1
+ import { $ as SandboxExecutionError, A as requireFilesystem, B as UnsupportedStdinCloseError, C as DEFAULT_TAIL_LINES, D as editFileTool, F as getRecommendedIsolation, G as validateSandboxFileMode, H as assertModesUnsupported, I as isIsolationAvailable, J as IsolationUnavailableError, K as MountManager, L as SandboxProcessManager, M as requireWorkspace, N as LocalSandbox, O as deleteFileTool, P as detectIsolation, Q as SandboxError, R as MastraSandbox, S as executeCommandTool, U as supportsComputer, V as MAX_SANDBOX_FILE_MODE, W as supportsNetworking, X as MountNotSupportedError, Y as MountError, Z as SandboxAbortError, _ as readFileTool, a as normalizeFactorySandboxSettings, at as LocalFilesystem, b as indexContentTool, c as formatSkillActivation, ct as callLifecycle, d as CompositeVersionedSkillSource, et as SandboxNotReadyError, f as VersionedSkillSource, g as searchTool, h as writeFileTool, i as isFactorySandbox, j as requireSandbox, k as applyPatchTool, l as collectSkillForPublish, lt as WORKSPACE_TOOLS, m as resolveToolConfig, n as FactorySandbox, nt as SandboxUnsupportedFeatureError, o as Workspace, ot as MastraFilesystem, p as createWorkspaceTools, q as FilesystemNotMountableError, r as describeFactorySandbox, s as createSkillTools, st as CompositeFilesystem, t as FACTORY_SANDBOX_BRAND, tt as SandboxTimeoutError, u as publishSkillFromSource, ut as WORKSPACE_TOOLS_PREFIX, v as mkdirTool, w as truncateOutput, x as fileStatTool, y as listFilesTool, z as ProcessHandle } from "../workspace-DY2Nxiyi.js";
2
2
  import { _ as WorkspaceError, a as FileReadRequiredError, b as WorkspaceReadOnlyError, c as FilesystemNotReadyError, d as PermissionError, f as SandboxFeatureNotSupportedError, g as UnsupportedGrepPatternError, h as StaleFileError, i as FileNotFoundError, l as IsDirectoryError, m as SearchNotAvailableError, n as DirectoryNotFoundError, o as FilesystemError, p as SandboxNotAvailableError, r as FileExistsError, s as FilesystemNotAvailableError, t as DirectoryNotEmptyError, u as NotDirectoryError, v as WorkspaceNotAvailableError, y as WorkspaceNotReadyError } from "../errors-CzFYpCHw.js";
3
3
  import { b as getMimeType, f as createGlobMatcher, h as matchGlob, l as LocalSkillSource, m as isGlobPattern, p as extractGlobBase } from "../workspace-skills-38OY32_b.js";
4
4
  export { CompositeFilesystem, CompositeVersionedSkillSource, DEFAULT_TAIL_LINES, DirectoryNotEmptyError, DirectoryNotFoundError, FACTORY_SANDBOX_BRAND, FactorySandbox, FileExistsError, FileNotFoundError, FileReadRequiredError, FilesystemError, FilesystemNotAvailableError, FilesystemNotMountableError, FilesystemNotReadyError, IsDirectoryError, IsolationUnavailableError, LocalFilesystem, LocalSandbox, LocalSkillSource, MAX_SANDBOX_FILE_MODE, MastraFilesystem, MastraSandbox, MountError, MountManager, MountNotSupportedError, NotDirectoryError, PermissionError, ProcessHandle, SandboxAbortError, SandboxError, SandboxExecutionError, SandboxFeatureNotSupportedError, SandboxNotAvailableError, SandboxNotReadyError, SandboxProcessManager, SandboxTimeoutError, SandboxUnsupportedFeatureError, SearchNotAvailableError, StaleFileError, UnsupportedGrepPatternError, UnsupportedStdinCloseError, VersionedSkillSource, WORKSPACE_TOOLS, WORKSPACE_TOOLS_PREFIX, Workspace, WorkspaceError, WorkspaceNotAvailableError, WorkspaceNotReadyError, WorkspaceReadOnlyError, applyPatchTool, assertModesUnsupported, callLifecycle, collectSkillForPublish, createGlobMatcher, createSkillTools, createWorkspaceTools, deleteFileTool, describeFactorySandbox, detectIsolation, editFileTool, executeCommandTool, extractGlobBase, fileStatTool, formatSkillActivation, getMimeType, getRecommendedIsolation, indexContentTool, isFactorySandbox, isGlobPattern, isIsolationAvailable, listFilesTool, matchGlob, mkdirTool, normalizeFactorySandboxSettings, publishSkillFromSource, readFileTool, requireFilesystem, requireSandbox, requireWorkspace, resolveToolConfig, searchTool, supportsComputer, supportsNetworking, truncateOutput, validateSandboxFileMode, writeFileTool };
@@ -160,9 +160,11 @@ export declare class LocalSandbox extends MastraSandbox<string> {
160
160
  private _activeMountPaths;
161
161
  /** Snapshot of `readWritePaths` from ctor; entries here are never removed on unmount. */
162
162
  private readonly _initialReadWritePaths;
163
- /** Refcount for isolation paths added by mounts (not present in `_initialReadWritePaths`). */
163
+ /** Snapshot of `denyWritePaths` from ctor; entries here are never removed on unmount. */
164
+ private readonly _initialDenyWritePaths;
165
+ /** Refcount for isolation paths added by mounts, keyed by `<list>:<path>`. */
164
166
  private _mountIsolationRefCount;
165
- /** Normalized mount path → canonical isolation path recorded for that mount. */
167
+ /** Normalized mount path → canonical isolation path and the list it was added to. */
166
168
  private _mountPathToIsolationPath;
167
169
  /** Named checkpoint to seed from on start and persist to on snapshot. */
168
170
  private readonly _checkpointName?;
@@ -300,20 +302,27 @@ export declare class LocalSandbox extends MastraSandbox<string> {
300
302
  */
301
303
  private checkMarkerFile;
302
304
  /**
303
- * Dynamically add a mount path to the sandbox isolation allowlist.
305
+ * Dynamically add a mount path to the sandbox isolation config.
304
306
  *
305
- * - Seatbelt: pushes to readWritePaths (wrapCommand reads config each call)
306
- * - Bwrap: pushes to readWritePaths (buildBwrapCommand reads config each call)
307
+ * Read-write mounts go to `readWritePaths`; mounts whose filesystem is
308
+ * `readOnly` go to `denyWritePaths` so subprocesses can read but never write
309
+ * them, matching what file tools enforce. Both backends read the config on
310
+ * every wrapCommand() call, so the change takes effect immediately.
307
311
  *
308
312
  * Local mounts are symlinks under `workingDirectory`. Bubblewrap cannot
309
313
  * `--bind` a symlink (it fails with "Unable to mount source on destination"),
310
314
  * so we store the canonical path (`realpath`) of the mount point — the same
311
315
  * directory the symlink refers to.
316
+ *
317
+ * Returns an error when a read-only mount can't be resolved: a write denial on
318
+ * the unresolved symlink wouldn't cover the directory writes actually land in.
312
319
  */
313
320
  private addMountPathToIsolation;
321
+ /** Undo a mount whose isolation couldn't be applied and record it as failed. */
322
+ private failMountIsolation;
314
323
  /**
315
- * Reverse {@link addMountPathToIsolation}: drop refcounted paths from the allowlist on unmount
316
- * while preserving user-provided `readWritePaths` from construction.
324
+ * Reverse {@link addMountPathToIsolation}: drop refcounted paths from the isolation
325
+ * config on unmount while preserving user-provided paths from construction.
317
326
  */
318
327
  private removeMountIsolationForPath;
319
328
  /**
@@ -30,6 +30,15 @@ export interface NativeSandboxConfig {
30
30
  * By default, only the workspace directory has write access.
31
31
  */
32
32
  readWritePaths?: string[];
33
+ /**
34
+ * Paths that are readable but never writable, even when nested inside the
35
+ * workspace or a `readWritePaths` entry. Applied after every write grant so
36
+ * it always wins — including when the same directory is also mounted
37
+ * read-write elsewhere. Mounted filesystems with `readOnly: true` are added
38
+ * here automatically. Ignored when a custom `bwrapArgs` or user-written
39
+ * `seatbeltProfilePath` replaces the generated policy.
40
+ */
41
+ denyWritePaths?: string[];
33
42
  /**
34
43
  * Allow executing system binaries (node, python, etc.)
35
44
  * When false, only binaries within the workspace can be executed.
@@ -60,7 +69,8 @@ export interface NativeSandboxConfig {
60
69
  * Spawned processes can read but not write files in the working directory.
61
70
  * Enforced at the OS level (seatbelt profile / bwrap --ro-bind); ignored when isolation is 'none'.
62
71
  * Exceptions:
63
- * - Paths listed in `readWritePaths` and mounted filesystem targets remain writable.
72
+ * - Paths listed in `readWritePaths` and mounted filesystem targets remain writable,
73
+ * except mounts whose filesystem is `readOnly` (see `denyWritePaths`).
64
74
  * - Providing custom `bwrapArgs` or `seatbeltProfilePath` replaces the generated
65
75
  * sandbox policy and may bypass this read-only restriction entirely.
66
76
  *
@@ -3834,6 +3834,7 @@ function generateSeatbeltProfile(workspacePath, config) {
3834
3834
  ]) if (config.readOnly) lines.push(`(allow file-write* (require-all (subpath ${escapePath(tempPath)}) (require-not (subpath ${escapePath(canonicalWorkspacePath)}))))`);
3835
3835
  else lines.push(`(allow file-write* (subpath ${escapePath(tempPath)}))`);
3836
3836
  for (const p of config.readWritePaths ?? []) lines.push(`(allow file-write* (subpath ${escapePath(canonicalizePath(p))}))`);
3837
+ for (const p of config.denyWritePaths ?? []) lines.push(`(deny file-write* (subpath ${escapePath(canonicalizePath(p))}))`);
3837
3838
  lines.push("");
3838
3839
  lines.push("; Network");
3839
3840
  if (config.allowNetwork) lines.push("(allow network*)");
@@ -3928,6 +3929,7 @@ function buildBwrapCommand(command, workspacePath, config) {
3928
3929
  if (config.readOnly) bwrapArgs.push("--ro-bind", workspacePath, workspacePath);
3929
3930
  else bwrapArgs.push("--bind", workspacePath, workspacePath);
3930
3931
  for (const path of config.readWritePaths ?? []) bwrapArgs.push("--bind", path, path);
3932
+ for (const path of config.denyWritePaths ?? []) bwrapArgs.push("--ro-bind", path, path);
3931
3933
  bwrapArgs.push("--dev", "/dev");
3932
3934
  bwrapArgs.push("--chdir", workspacePath);
3933
3935
  bwrapArgs.push("--die-with-parent");
@@ -4052,9 +4054,11 @@ var LocalSandbox = class LocalSandbox extends MastraSandbox {
4052
4054
  _activeMountPaths = /* @__PURE__ */ new Set();
4053
4055
  /** Snapshot of `readWritePaths` from ctor; entries here are never removed on unmount. */
4054
4056
  _initialReadWritePaths;
4055
- /** Refcount for isolation paths added by mounts (not present in `_initialReadWritePaths`). */
4057
+ /** Snapshot of `denyWritePaths` from ctor; entries here are never removed on unmount. */
4058
+ _initialDenyWritePaths;
4059
+ /** Refcount for isolation paths added by mounts, keyed by `<list>:<path>`. */
4056
4060
  _mountIsolationRefCount = /* @__PURE__ */ new Map();
4057
- /** Normalized mount path → canonical isolation path recorded for that mount. */
4061
+ /** Normalized mount path → canonical isolation path and the list it was added to. */
4058
4062
  _mountPathToIsolationPath = /* @__PURE__ */ new Map();
4059
4063
  /** Named checkpoint to seed from on start and persist to on snapshot. */
4060
4064
  _checkpointName;
@@ -4094,9 +4098,11 @@ var LocalSandbox = class LocalSandbox extends MastraSandbox {
4094
4098
  this._nativeSandboxConfig = {
4095
4099
  ...options.nativeSandbox,
4096
4100
  readWritePaths: [...options.nativeSandbox?.readWritePaths ?? []],
4097
- readOnlyPaths: [...options.nativeSandbox?.readOnlyPaths ?? []]
4101
+ readOnlyPaths: [...options.nativeSandbox?.readOnlyPaths ?? []],
4102
+ denyWritePaths: [...options.nativeSandbox?.denyWritePaths ?? []]
4098
4103
  };
4099
4104
  this._initialReadWritePaths = new Set(this._nativeSandboxConfig.readWritePaths ?? []);
4105
+ this._initialDenyWritePaths = new Set(this._nativeSandboxConfig.denyWritePaths ?? []);
4100
4106
  this.isolation = requestedIsolation;
4101
4107
  this._instructionsOverride = options.instructions;
4102
4108
  this._checkpointName = options.checkpointName;
@@ -4124,7 +4130,8 @@ var LocalSandbox = class LocalSandbox extends MastraSandbox {
4124
4130
  nativeSandbox: {
4125
4131
  ...this._nativeSandboxConfig,
4126
4132
  readWritePaths: [...this._initialReadWritePaths],
4127
- readOnlyPaths: [...this._nativeSandboxConfig.readOnlyPaths ?? []]
4133
+ readOnlyPaths: [...this._nativeSandboxConfig.readOnlyPaths ?? []],
4134
+ denyWritePaths: [...this._initialDenyWritePaths]
4128
4135
  },
4129
4136
  ...this._instructionsOverride !== void 0 && { instructions: this._instructionsOverride },
4130
4137
  ...(options.checkpointName ?? this._checkpointName) !== void 0 && { checkpointName: options.checkpointName ?? this._checkpointName },
@@ -4362,7 +4369,8 @@ var LocalSandbox = class LocalSandbox extends MastraSandbox {
4362
4369
  isolationConfig: this.isolation !== "none" ? {
4363
4370
  allowNetwork: this._nativeSandboxConfig.allowNetwork ?? false,
4364
4371
  readOnlyPaths: this._nativeSandboxConfig.readOnlyPaths,
4365
- readWritePaths: this._nativeSandboxConfig.readWritePaths
4372
+ readWritePaths: this._nativeSandboxConfig.readWritePaths,
4373
+ denyWritePaths: this._nativeSandboxConfig.denyWritePaths
4366
4374
  } : void 0
4367
4375
  }
4368
4376
  };
@@ -4433,7 +4441,8 @@ var LocalSandbox = class LocalSandbox extends MastraSandbox {
4433
4441
  config
4434
4442
  });
4435
4443
  this._activeMountPaths.add(mountPath);
4436
- this.addMountPathToIsolation(mountPath, hostPath);
4444
+ const isolationError = this.addMountPathToIsolation(mountPath, hostPath, filesystem.readOnly === true);
4445
+ if (isolationError) return this.failMountIsolation(filesystem, mountPath, config, isolationError);
4437
4446
  return {
4438
4447
  success: true,
4439
4448
  mountPath
@@ -4544,7 +4553,8 @@ var LocalSandbox = class LocalSandbox extends MastraSandbox {
4544
4553
  });
4545
4554
  this._activeMountPaths.add(mountPath);
4546
4555
  await this.writeMarkerFile(mountPath, hostPath);
4547
- this.addMountPathToIsolation(mountPath, hostPath);
4556
+ const isolationError = this.addMountPathToIsolation(mountPath, hostPath, filesystem.readOnly === true);
4557
+ if (isolationError) return this.failMountIsolation(filesystem, mountPath, config, isolationError);
4548
4558
  this.logger.debug("Mounted", {
4549
4559
  mountPath,
4550
4560
  hostPath
@@ -4657,53 +4667,91 @@ var LocalSandbox = class LocalSandbox extends MastraSandbox {
4657
4667
  }
4658
4668
  }
4659
4669
  /**
4660
- * Dynamically add a mount path to the sandbox isolation allowlist.
4670
+ * Dynamically add a mount path to the sandbox isolation config.
4661
4671
  *
4662
- * - Seatbelt: pushes to readWritePaths (wrapCommand reads config each call)
4663
- * - Bwrap: pushes to readWritePaths (buildBwrapCommand reads config each call)
4672
+ * Read-write mounts go to `readWritePaths`; mounts whose filesystem is
4673
+ * `readOnly` go to `denyWritePaths` so subprocesses can read but never write
4674
+ * them, matching what file tools enforce. Both backends read the config on
4675
+ * every wrapCommand() call, so the change takes effect immediately.
4664
4676
  *
4665
4677
  * Local mounts are symlinks under `workingDirectory`. Bubblewrap cannot
4666
4678
  * `--bind` a symlink (it fails with "Unable to mount source on destination"),
4667
4679
  * so we store the canonical path (`realpath`) of the mount point — the same
4668
4680
  * directory the symlink refers to.
4681
+ *
4682
+ * Returns an error when a read-only mount can't be resolved: a write denial on
4683
+ * the unresolved symlink wouldn't cover the directory writes actually land in.
4669
4684
  */
4670
- addMountPathToIsolation(mountPath, hostPath) {
4685
+ addMountPathToIsolation(mountPath, hostPath, readOnly) {
4671
4686
  if (this.isolation === "none") return;
4672
4687
  const normMount = normalizeMountPath(mountPath);
4673
- if (this._mountPathToIsolationPath.has(normMount)) return;
4688
+ const list = readOnly ? "denyWritePaths" : "readWritePaths";
4689
+ const existing = this._mountPathToIsolationPath.get(normMount);
4690
+ if (existing?.list === list) return;
4691
+ if (existing) this.removeMountIsolationForPath(normMount);
4674
4692
  let isolationPath = hostPath;
4675
4693
  try {
4676
4694
  isolationPath = realpathSync(hostPath);
4677
- } catch {}
4678
- if (!this._nativeSandboxConfig.readWritePaths) this._nativeSandboxConfig = {
4695
+ } catch {
4696
+ if (readOnly) return `Cannot mount read-only filesystem at ${hostPath}: its source could not be resolved, so writes to it can't be denied to sandboxed commands.`;
4697
+ this.logger.warn("Could not resolve mount path for isolation; using unresolved path", { hostPath });
4698
+ }
4699
+ if (!this._nativeSandboxConfig[list]) this._nativeSandboxConfig = {
4679
4700
  ...this._nativeSandboxConfig,
4680
- readWritePaths: []
4701
+ [list]: []
4681
4702
  };
4682
- const paths = this._nativeSandboxConfig.readWritePaths;
4703
+ const paths = this._nativeSandboxConfig[list];
4683
4704
  if (!paths.includes(isolationPath)) paths.push(isolationPath);
4684
- if (!this._initialReadWritePaths.has(isolationPath)) this._mountIsolationRefCount.set(isolationPath, (this._mountIsolationRefCount.get(isolationPath) ?? 0) + 1);
4685
- this._mountPathToIsolationPath.set(normMount, isolationPath);
4705
+ if (!(readOnly ? this._initialDenyWritePaths : this._initialReadWritePaths).has(isolationPath)) {
4706
+ const key = `${list}:${isolationPath}`;
4707
+ this._mountIsolationRefCount.set(key, (this._mountIsolationRefCount.get(key) ?? 0) + 1);
4708
+ }
4709
+ this._mountPathToIsolationPath.set(normMount, {
4710
+ path: isolationPath,
4711
+ list
4712
+ });
4713
+ }
4714
+ /** Undo a mount whose isolation couldn't be applied and record it as failed. */
4715
+ async failMountIsolation(filesystem, mountPath, config, error) {
4716
+ this.logger.error("Could not apply mount isolation", {
4717
+ mountPath,
4718
+ error
4719
+ });
4720
+ await this.unmount(mountPath);
4721
+ this.mounts.set(mountPath, {
4722
+ filesystem,
4723
+ state: "error",
4724
+ config,
4725
+ error
4726
+ });
4727
+ return {
4728
+ success: false,
4729
+ mountPath,
4730
+ error
4731
+ };
4686
4732
  }
4687
4733
  /**
4688
- * Reverse {@link addMountPathToIsolation}: drop refcounted paths from the allowlist on unmount
4689
- * while preserving user-provided `readWritePaths` from construction.
4734
+ * Reverse {@link addMountPathToIsolation}: drop refcounted paths from the isolation
4735
+ * config on unmount while preserving user-provided paths from construction.
4690
4736
  */
4691
4737
  removeMountIsolationForPath(mountPath) {
4692
4738
  if (this.isolation === "none") return;
4693
4739
  const normMount = normalizeMountPath(mountPath);
4694
- const isolationPath = this._mountPathToIsolationPath.get(normMount);
4695
- if (isolationPath === void 0) return;
4740
+ const entry = this._mountPathToIsolationPath.get(normMount);
4741
+ if (entry === void 0) return;
4696
4742
  this._mountPathToIsolationPath.delete(normMount);
4697
- if (this._initialReadWritePaths.has(isolationPath)) return;
4698
- const next = (this._mountIsolationRefCount.get(isolationPath) ?? 0) - 1;
4743
+ const { path: isolationPath, list } = entry;
4744
+ if ((list === "denyWritePaths" ? this._initialDenyWritePaths : this._initialReadWritePaths).has(isolationPath)) return;
4745
+ const key = `${list}:${isolationPath}`;
4746
+ const next = (this._mountIsolationRefCount.get(key) ?? 0) - 1;
4699
4747
  if (next <= 0) {
4700
- this._mountIsolationRefCount.delete(isolationPath);
4701
- const paths = this._nativeSandboxConfig.readWritePaths;
4748
+ this._mountIsolationRefCount.delete(key);
4749
+ const paths = this._nativeSandboxConfig[list];
4702
4750
  if (paths) {
4703
4751
  const idx = paths.indexOf(isolationPath);
4704
4752
  if (idx !== -1) paths.splice(idx, 1);
4705
4753
  }
4706
- } else this._mountIsolationRefCount.set(isolationPath, next);
4754
+ } else this._mountIsolationRefCount.set(key, next);
4707
4755
  }
4708
4756
  /**
4709
4757
  * Resolve a virtual mount path to a host filesystem path.
@@ -6685,6 +6733,159 @@ function splitTail(output, tail) {
6685
6733
  };
6686
6734
  }
6687
6735
  /**
6736
+ * tokenx is synchronous and allocates per word, so running it over a multi-MB
6737
+ * output blocks the event loop for seconds. Outputs up to this many chars per
6738
+ * token of budget are counted and cut exactly as before; longer ones never reach
6739
+ * tokenx whole (see `countTokensOver` and `sliceEdge`).
6740
+ */
6741
+ const WINDOW_CHARS_PER_TOKEN = 32;
6742
+ /**
6743
+ * tokenx never gives a non-whitespace segment fewer than one token per this many
6744
+ * UTF-16 chars: 6 by default, and up to 4 code points (8 chars when astral) for
6745
+ * its language rules. So text with more non-whitespace chars than
6746
+ * `limit * MAX_CHARS_PER_TOKEN` is over `limit`.
6747
+ */
6748
+ const MAX_CHARS_PER_TOKEN = 8;
6749
+ const WHITESPACE_RUN_RE = /\s+/g;
6750
+ const STRUCTURED_WHITESPACE_RE = /\n\s/;
6751
+ const WS = 0;
6752
+ const PUNCT = 1;
6753
+ const DIGIT = 2;
6754
+ const WORD = 3;
6755
+ const CHAR_CLASS = (/* @__PURE__ */ new Uint8Array(128)).fill(WORD);
6756
+ for (const c of " \n\r\v\f") CHAR_CLASS[c.charCodeAt(0)] = WS;
6757
+ for (const c of ".,!?;(){}[]<>:/\\|@#$%^&*+=`~_\"-") CHAR_CLASS[c.charCodeAt(0)] = PUNCT;
6758
+ for (let c = 48; c <= 57; c++) CHAR_CLASS[c] = DIGIT;
6759
+ /** Same set as the regex `\s`, which is what tokenx splits words on. */
6760
+ function isWhitespace(code) {
6761
+ return code === 160 || code === 5760 || code >= 8192 && code <= 8202 || code === 8232 || code === 8233 || code === 8239 || code === 8287 || code === 12288 || code === 65279;
6762
+ }
6763
+ function runTokens(kind, length, onlyDigits) {
6764
+ if (kind === WS) return 0;
6765
+ if (length <= 3) return 1;
6766
+ if (kind === PUNCT) return Math.ceil(length / 2);
6767
+ return onlyDigits ? Math.ceil(length / 3) : Math.ceil(length / 6);
6768
+ }
6769
+ /**
6770
+ * One pass over char codes with no allocations: an approximate token count
6771
+ * (tokenx's rules for ASCII text, used only for the "of ~N tokens" total) and
6772
+ * the number of non-whitespace chars.
6773
+ */
6774
+ function scanTokens(text) {
6775
+ let approx = 0;
6776
+ let nonWhitespace = 0;
6777
+ let kind = -1;
6778
+ let length = 0;
6779
+ let onlyDigits = true;
6780
+ for (let i = 0; i < text.length; i++) {
6781
+ const code = text.charCodeAt(i);
6782
+ const cls = code < 128 ? CHAR_CLASS[code] : isWhitespace(code) ? WS : WORD;
6783
+ const runKind = cls === DIGIT ? WORD : cls;
6784
+ if (runKind !== kind) {
6785
+ if (length) approx += runTokens(kind, length, onlyDigits);
6786
+ kind = runKind;
6787
+ length = 0;
6788
+ onlyDigits = true;
6789
+ }
6790
+ length++;
6791
+ if (cls !== WS) nonWhitespace++;
6792
+ if (cls !== DIGIT) onlyDigits = false;
6793
+ }
6794
+ if (length) approx += runTokens(kind, length, onlyDigits);
6795
+ return {
6796
+ approx,
6797
+ nonWhitespace
6798
+ };
6799
+ }
6800
+ /**
6801
+ * Exact token count of `output` when it may fit `limit`, else an approximation.
6802
+ * Returns `undefined` when the output fits, so callers return it as is.
6803
+ */
6804
+ function countTokensOver(output, limit) {
6805
+ if (output.length <= Math.max(limit, 1) * WINDOW_CHARS_PER_TOKEN) {
6806
+ const exact = estimateTokenCount(output);
6807
+ return exact <= limit ? void 0 : exact;
6808
+ }
6809
+ const { approx, nonWhitespace } = scanTokens(output);
6810
+ if (nonWhitespace > limit * MAX_CHARS_PER_TOKEN) return approx;
6811
+ const exact = estimateTokenCount(output.replace(WHITESPACE_RUN_RE, (run) => STRUCTURED_WHITESPACE_RE.test(run) ? "\n " : " "));
6812
+ return exact <= limit ? void 0 : exact;
6813
+ }
6814
+ /**
6815
+ * `budget` tokens from one end of `output`. Outputs within the overall `limit`'s
6816
+ * size cap are cut exactly as before, by `sliceByTokensSafe(output, 0, budget)`
6817
+ * (`'head'`) or `sliceByTokensSafe(output, -budget)` (`'tail'`). Longer ones hand
6818
+ * tokenx only a window at that end, measured as tokenx sees it: whitespace runs
6819
+ * are collapsed (see `countTokensOver`), so padding can't crowd real text out of
6820
+ * the window. The cut is mapped back to the original text, whitespace and all.
6821
+ *
6822
+ * For those longer outputs the cut is approximate: it fits `budget` by tokenx's
6823
+ * count of the kept text, but can land elsewhere than tokenizing the whole output
6824
+ * would. tokenx counts a segment by its whole length, so a window that ends inside
6825
+ * a long segment counts it differently (at a 2,000-token budget, 65,000 'a' then
6826
+ * 'é' keeps 12,000 chars here and 6,000 when the whole output is tokenized).
6827
+ */
6828
+ function sliceEdge(output, budget, limit, side) {
6829
+ if (output.length <= Math.max(limit, 1) * WINDOW_CHARS_PER_TOKEN) return side === "head" ? sliceByTokensSafe(output, 0, budget) : sliceByTokensSafe(output, -budget);
6830
+ const target = Math.max(budget, 1) * WINDOW_CHARS_PER_TOKEN;
6831
+ let size = 0;
6832
+ let inWhitespace = false;
6833
+ let edge = side === "head" ? 0 : output.length;
6834
+ while (side === "head" ? edge < output.length : edge > 0) {
6835
+ const code = output.charCodeAt(side === "head" ? edge : edge - 1);
6836
+ const whitespace = code < 128 ? CHAR_CLASS[code] === WS : isWhitespace(code);
6837
+ const cost = whitespace ? inWhitespace ? 0 : 2 : 1;
6838
+ if (size + cost > target) break;
6839
+ size += cost;
6840
+ inWhitespace = whitespace;
6841
+ edge += side === "head" ? 1 : -1;
6842
+ }
6843
+ const window = side === "head" ? output.slice(0, edge) : output.slice(edge);
6844
+ const runs = [];
6845
+ let collapsed = "";
6846
+ let last = 0;
6847
+ for (const match of window.matchAll(WHITESPACE_RUN_RE)) {
6848
+ collapsed += window.slice(last, match.index);
6849
+ const replacement = STRUCTURED_WHITESPACE_RE.test(match[0]) ? "\n " : " ";
6850
+ runs.push({
6851
+ collapsedStart: collapsed.length,
6852
+ collapsedEnd: collapsed.length + replacement.length,
6853
+ start: match.index,
6854
+ end: match.index + match[0].length
6855
+ });
6856
+ collapsed += replacement;
6857
+ last = match.index + match[0].length;
6858
+ }
6859
+ collapsed += window.slice(last);
6860
+ const toWindowIndex = (index) => {
6861
+ let shift = 0;
6862
+ for (const run of runs) {
6863
+ if (index < run.collapsedStart) break;
6864
+ if (index <= run.collapsedEnd) return index === run.collapsedEnd ? run.end : run.start;
6865
+ shift = run.end - run.collapsedEnd;
6866
+ }
6867
+ return index + shift;
6868
+ };
6869
+ if (side === "head") return sliceSafe(window, 0, toWindowIndex(fitBudget(sliceByTokensSafe(collapsed, 0, budget), budget, side).length));
6870
+ const kept = fitBudget(sliceByTokensSafe(collapsed, -budget), budget, side);
6871
+ return sliceSafe(window, toWindowIndex(collapsed.length - kept.length));
6872
+ }
6873
+ /**
6874
+ * tokenx slices a segment by the chars-per-token of its language, picked from the
6875
+ * chars it contains, so a cut that drops the char that picked it (a lone 'ж' in a run
6876
+ * of CJK) can count several times over `budget` on its own. Recount the kept text,
6877
+ * which is no longer than the bounded input it was cut from, and cut it again until
6878
+ * it fits.
6879
+ */
6880
+ function fitBudget(kept, budget, side) {
6881
+ for (let tokens = estimateTokenCount(kept); kept.length > 0 && tokens > budget; tokens = estimateTokenCount(kept)) {
6882
+ const next = side === "head" ? sliceByTokensSafe(kept, 0, budget) : sliceByTokensSafe(kept, -budget);
6883
+ const length = next.length < kept.length ? next.length : Math.floor(kept.length * budget / tokens);
6884
+ kept = side === "head" ? sliceSafe(kept, 0, length) : sliceSafe(kept, kept.length - length);
6885
+ }
6886
+ return kept;
6887
+ }
6888
+ /**
6688
6889
  * Token-based output limit. Truncates output to fit within a token budget.
6689
6890
  * Uses tokenx for fast token estimation and truncates at the token level
6690
6891
  * (not line boundaries) to maximise use of the budget.
@@ -6697,9 +6898,9 @@ function splitTail(output, tail) {
6697
6898
  */
6698
6899
  async function applyTokenLimit(output, limit = DEFAULT_MAX_OUTPUT_TOKENS, from = "start") {
6699
6900
  if (!output) return output;
6700
- const totalTokens = estimateTokenCount(output);
6701
- if (totalTokens <= limit) return output;
6702
- const kept = from === "start" ? sliceByTokensSafe(output, -limit) : sliceByTokensSafe(output, 0, limit);
6901
+ const totalTokens = countTokensOver(output, limit);
6902
+ if (totalTokens === void 0) return output;
6903
+ const kept = from === "start" ? sliceEdge(output, limit, limit, "tail") : sliceEdge(output, limit, limit, "head");
6703
6904
  const position = from === "start" ? "last" : "first";
6704
6905
  return from === "start" ? `[output truncated: showing ${position} ~${limit} of ~${totalTokens} tokens]\n${kept}` : `${kept}\n[output truncated: showing ${position} ~${limit} of ~${totalTokens} tokens]`;
6705
6906
  }
@@ -6709,12 +6910,12 @@ async function applyTokenLimit(output, limit = DEFAULT_MAX_OUTPUT_TOKENS, from =
6709
6910
  */
6710
6911
  function sandwich(output, limit, headRatio, firstLine) {
6711
6912
  if (!output) return output;
6712
- const totalTokens = estimateTokenCount(output);
6713
- if (totalTokens <= limit) return output;
6913
+ const totalTokens = countTokensOver(output, limit);
6914
+ if (totalTokens === void 0) return output;
6714
6915
  const headBudget = Math.floor(limit * headRatio);
6715
6916
  const tailBudget = limit - headBudget;
6716
- let head = headBudget > 0 ? sliceByTokensSafe(output, 0, headBudget) : "";
6717
- let tail = tailBudget > 0 ? sliceByTokensSafe(output, -tailBudget) : "";
6917
+ let head = headBudget > 0 ? sliceEdge(output, headBudget, limit, "head") : "";
6918
+ let tail = tailBudget > 0 ? sliceEdge(output, tailBudget, limit, "tail") : "";
6718
6919
  const headEnd = head.length;
6719
6920
  let tailStart = output.length - tail.length;
6720
6921
  head = head.replace(/\r?\n$/, "");