thursday-agent 0.17.2 → 0.19.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.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +4 -2
- package/.next/build-manifest.json +3 -3
- package/.next/prerender-manifest.json +3 -3
- package/.next/routes-manifest.json +28 -12
- package/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +12 -12
- package/.next/server/app/_not-found.segments/_full.segment.rsc +12 -12
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +11 -11
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/api/artifact/route.js +7 -7
- package/.next/server/app/api/artifact/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/memory/files/route.js +4 -4
- package/.next/server/app/api/bot/memory/files/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/memory/route.js +4 -4
- package/.next/server/app/api/bot/memory/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/route.js +4 -4
- package/.next/server/app/api/bot/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/thread/[id]/route.js +1 -1
- package/.next/server/app/api/bot/thread/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/thread/file/route/app-paths-manifest.json +3 -0
- package/.next/server/app/api/bot/thread/file/route.js +29 -0
- package/.next/server/app/api/bot/thread/file/route.js.nft.json +1 -0
- package/.next/server/app/api/bot/thread/file/route_client-reference-manifest.js +3 -0
- package/.next/server/app/api/bot/thread/route.js +1 -1
- package/.next/server/app/api/bot/thread/route.js.nft.json +1 -1
- package/.next/server/app/api/config/route.js +1 -1
- package/.next/server/app/api/config/route.js.nft.json +1 -1
- package/.next/server/app/api/events/route.js +2 -2
- package/.next/server/app/api/events/route.js.nft.json +1 -1
- package/.next/server/app/api/favicon/[host]/route.js.nft.json +1 -1
- package/.next/server/app/api/file/[...path]/route.js +4 -4
- package/.next/server/app/api/file/[...path]/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/automatic/route.js +3 -3
- package/.next/server/app/api/llm-model/automatic/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/catalog/[provider]/route/app-paths-manifest.json +3 -0
- package/.next/server/app/api/llm-model/catalog/{route.js → [provider]/route.js} +8 -8
- package/.next/server/app/api/llm-model/catalog/[provider]/route.js.nft.json +1 -0
- package/.next/server/app/api/llm-model/catalog/[provider]/route_client-reference-manifest.js +3 -0
- package/.next/server/app/api/llm-model/credits/[provider]/route/app-paths-manifest.json +3 -0
- package/.next/server/app/api/llm-model/credits/[provider]/route/build-manifest.json +12 -0
- package/.next/server/app/api/llm-model/credits/[provider]/route/server-reference-manifest.json +4 -0
- package/.next/server/app/api/llm-model/credits/{route.js → [provider]/route.js} +8 -8
- package/.next/server/app/api/llm-model/credits/[provider]/route.js.map +5 -0
- package/.next/server/app/api/llm-model/credits/[provider]/route.js.nft.json +1 -0
- package/.next/server/app/api/llm-model/credits/[provider]/route_client-reference-manifest.js +3 -0
- package/.next/server/app/api/llm-model/route.js +1 -1
- package/.next/server/app/api/llm-model/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/subscription/route.js +1 -1
- package/.next/server/app/api/llm-model/subscription/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/[name]/route.js +1 -1
- package/.next/server/app/api/mcp/[name]/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/oauth/callback/route.js +2 -2
- package/.next/server/app/api/mcp/oauth/callback/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/route.js +1 -1
- package/.next/server/app/api/mcp/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/tools/route.js +1 -1
- package/.next/server/app/api/mcp/tools/route.js.nft.json +1 -1
- package/.next/server/app/api/memory/edit/route.js +12 -12
- package/.next/server/app/api/memory/edit/route.js.nft.json +1 -1
- package/.next/server/app/api/memory/route.js +1 -1
- package/.next/server/app/api/memory/route.js.nft.json +1 -1
- package/.next/server/app/api/reach/route.js +17 -17
- package/.next/server/app/api/reach/route.js.nft.json +1 -1
- package/.next/server/app/api/routine/route.js +6 -6
- package/.next/server/app/api/routine/route.js.nft.json +1 -1
- package/.next/server/app/api/running/route/app-paths-manifest.json +3 -0
- package/.next/server/app/api/running/route/build-manifest.json +12 -0
- package/.next/server/app/api/running/route/server-reference-manifest.json +4 -0
- package/.next/server/app/api/running/route.js +10 -0
- package/.next/server/app/api/running/route.js.map +5 -0
- package/.next/server/app/api/running/route.js.nft.json +1 -0
- package/.next/server/app/api/running/route_client-reference-manifest.js +3 -0
- package/.next/server/app/api/signins/route.js +4 -4
- package/.next/server/app/api/signins/route.js.nft.json +1 -1
- package/.next/server/app/api/skills/[source]/[name]/route.js +7 -7
- package/.next/server/app/api/skills/[source]/[name]/route.js.nft.json +1 -1
- package/.next/server/app/api/skills/route.js +6 -6
- package/.next/server/app/api/skills/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/call/end/route.js +1 -1
- package/.next/server/app/api/thursday/call/end/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/call/route.js +1 -1
- package/.next/server/app/api/thursday/call/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/settings/route.js +1 -1
- package/.next/server/app/api/thursday/settings/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/text/route.js +12 -12
- package/.next/server/app/api/thursday/text/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/tool-call/route.js +13 -13
- package/.next/server/app/api/thursday/tool-call/route.js.nft.json +1 -1
- package/.next/server/app/api/workspace/files/route.js +7 -7
- package/.next/server/app/api/workspace/files/route.js.nft.json +1 -1
- package/.next/server/app/api/workspace/route.js +6 -6
- package/.next/server/app/api/workspace/route.js.nft.json +1 -1
- package/.next/server/app/artifact/[...path]/page/server-reference-manifest.json +94 -6
- package/.next/server/app/artifact/[...path]/page.js +9 -5
- package/.next/server/app/artifact/[...path]/page.js.nft.json +1 -1
- package/.next/server/app/artifact/[...path]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/favicon.ico/route.js.nft.json +1 -1
- package/.next/server/app/manifest.webmanifest/route.js.nft.json +1 -1
- package/.next/server/app/page/server-reference-manifest.json +161 -128
- package/.next/server/app/page.js +10 -9
- package/.next/server/app/page.js.nft.json +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +4 -2
- package/.next/server/chunks/[root-of-the-server]__00qyw01._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__02ra64t._.js +5 -0
- package/.next/server/chunks/{[root-of-the-server]__05dp5tr._.js → [root-of-the-server]__06ky9of._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__0b565-x._.js +7 -0
- package/.next/server/chunks/[root-of-the-server]__0bmtib_._.js +7 -0
- package/.next/server/chunks/[root-of-the-server]__0bqveex._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0brmiv2._.js +7 -0
- package/.next/server/chunks/[root-of-the-server]__0eivkvk._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__0f7m79q._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0g38-aj._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__0gvdr2h._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__0h656y-._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__0hm3tiq._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__0hzdqnv._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__0kzmxpg._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0mgyt8p._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__0mrk2it._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0o5s5-o._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__0p80i1n._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0qdoc_9._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__0qzho69._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0sm5xvm._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0v_kuor._.js +5 -0
- package/.next/server/chunks/{[root-of-the-server]__061o2_x._.js → [root-of-the-server]__0ypkfbu._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__1-18_pz._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__13hng6h._.js +1 -1
- package/.next/server/chunks/{[root-of-the-server]__01k3vi3._.js → [root-of-the-server]__14iga7p._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__16gn7zn._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__18e65_-._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1_04mcf._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__1_cgawk._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__1ceammd._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1ckt1yj._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1cu5f3z._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1dth047._.js +5 -0
- package/.next/server/chunks/{[root-of-the-server]__1k2qs1m._.js → [root-of-the-server]__1fc6v12._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__1hviq62._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__1ksm9m-._.js +12 -0
- package/.next/server/chunks/[root-of-the-server]__1m1q6u5._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1m_dmf6._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__1mys2c3._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__1ndi14y._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1p0njle._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__1p47fbb._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__1pugoq0._.js +1 -1
- package/.next/server/chunks/{[root-of-the-server]__0ts7ai0._.js → [root-of-the-server]__1trns9g._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__1ygplx1._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1zn039k._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__20w_g71._.js +3 -0
- package/.next/server/chunks/_01c32w9._.js +1 -1
- package/.next/server/chunks/_02bov6_._.js +1 -1
- package/.next/server/chunks/_06hnfi8._.js +2 -2
- package/.next/server/chunks/_06u9yo-._.js +1 -1
- package/.next/server/chunks/_08354bn._.js +12 -11
- package/.next/server/chunks/_08_-9ay._.js +7 -0
- package/.next/server/chunks/_08s4vft._.js +1 -1
- package/.next/server/chunks/_0bgjf07._.js +5 -0
- package/.next/server/chunks/_0c49lmw._.js +1 -1
- package/.next/server/chunks/_0fb6dvr._.js +1 -1
- package/.next/server/chunks/_0hgvg55._.js +1 -1
- package/.next/server/chunks/_0iw19ig._.js +1 -1
- package/.next/server/chunks/_0poi1t2._.js +1 -1
- package/.next/server/chunks/_0s8ao8z._.js +1 -1
- package/.next/server/chunks/_0t_7gji._.js +1 -1
- package/.next/server/chunks/_0ucx1jv._.js +1 -1
- package/.next/server/chunks/_0uzj57i._.js +1 -1
- package/.next/server/chunks/_0wyh244._.js +112 -0
- package/.next/server/chunks/_1-sk_q4._.js +1 -1
- package/.next/server/chunks/_108gsm8._.js +2 -2
- package/.next/server/chunks/_136j09a._.js +5 -5
- package/.next/server/chunks/_15negpy._.js +2 -2
- package/.next/server/chunks/_1d7og_q._.js +1 -1
- package/.next/server/chunks/_1dxq827._.js +2 -2
- package/.next/server/chunks/_1e54wxa._.js +1 -1
- package/.next/server/chunks/_1frcwj1._.js +1 -1
- package/.next/server/chunks/_1gn2r2q._.js +8 -6
- package/.next/server/chunks/_1gxankq._.js +2 -2
- package/.next/server/chunks/_1i3uucm._.js +1 -1
- package/.next/server/chunks/_1jvy78-._.js +5 -0
- package/.next/server/chunks/_1lg0lsu._.js +53 -0
- package/.next/server/chunks/_1njolhx._.js +294 -0
- package/.next/server/chunks/_1q6e56i._.js +8 -6
- package/.next/server/chunks/_1qgix-j._.js +1 -1
- package/.next/server/chunks/_1wtb-77._.js +294 -0
- package/.next/server/chunks/_1wwl_7o._.js +1 -1
- package/.next/server/chunks/_1y8w80a._.js +5 -5
- package/.next/server/chunks/_1yx285_._.js +3 -0
- package/.next/server/chunks/_20qn224._.js +3 -0
- package/.next/server/chunks/_211dn2c._.js +1 -1
- package/.next/server/chunks/_next-internal_server_app_api_bot_thread_file_route_actions_0q3be0o.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_llm-model_catalog_[provider]_route_actions_1i0449q.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_llm-model_credits_[provider]_route_actions_0iui9hz.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_running_route_actions_0o1g-aw.js +3 -0
- package/.next/server/chunks/config_ts_1g4sz5o._.js +1 -1
- package/.next/server/chunks/features_bot_08z387_._.js +3 -3
- package/.next/server/chunks/features_bot_0zy_q8y._.js +7 -7
- package/.next/server/chunks/features_bot_1dfrdsb._.js +7 -7
- package/.next/server/chunks/features_workspace_workspace_ts_13h82gv._.js +3 -3
- package/.next/server/chunks/features_workspace_workspace_ts_1iyjroj._.js +3 -3
- package/.next/server/chunks/{node_modules_1rosz79._.js → node_modules_035o7ku._.js} +1 -1
- package/.next/server/chunks/{node_modules_1er1u8w._.js → node_modules_0tn5t13._.js} +1 -1
- package/.next/server/chunks/{node_modules_103lpef._.js → node_modules_12oq3hr._.js} +1 -1
- package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_0g87zst._.js → node_modules_consola_dist_chunks_prompt_mjs_0yd5xa0._.js} +1 -1
- package/.next/server/chunks/ssr/[root-of-the-server]__04upd5v._.js +1 -1
- package/.next/server/chunks/ssr/[root-of-the-server]__0p0mv2u._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0sk5enu._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0xyaud4._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1-gi9sm._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__16nn3pe._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1867koj._.js +1 -1
- package/.next/server/chunks/ssr/[root-of-the-server]__1c8-7cw._.js +3 -0
- package/.next/server/chunks/ssr/{[root-of-the-server]__1d7usu0._.js → [root-of-the-server]__1qn0axo._.js} +2 -2
- package/.next/server/chunks/ssr/[root-of-the-server]__1tb5vve._.js +47 -0
- package/.next/server/chunks/ssr/_02cm0fr._.js +5 -0
- package/.next/server/chunks/ssr/{features_bot_1knyan7._.js → _07nmtxo._.js} +2 -2
- package/.next/server/chunks/ssr/_088vzgn._.js +1 -1
- package/.next/server/chunks/ssr/{_1dfv66y._.js → _0bg1u1j._.js} +2 -2
- package/.next/server/chunks/ssr/_0cv9tmv._.js +1 -1
- package/.next/server/chunks/ssr/{_10-_awu._.js → _0f9hx5p._.js} +2 -2
- package/.next/server/chunks/ssr/_0g9ula_._.js +3 -0
- package/.next/server/chunks/ssr/{_1aqjk-1._.js → _0irozu9._.js} +2 -2
- package/.next/server/chunks/ssr/{_123y-ah._.js → _0is8m6y._.js} +2 -2
- package/.next/server/chunks/ssr/_0iwsdp7._.js +3 -0
- package/.next/server/chunks/ssr/_0l7rjg5._.js +1 -1
- package/.next/server/chunks/ssr/{lib_logger_ts_0-olsze._.js → _0mfgsk-._.js} +4 -2
- package/.next/server/chunks/ssr/{_0fo4552._.js → _0nk80t6._.js} +53 -13
- package/.next/server/chunks/ssr/_0p6w0ef._.js +3 -0
- package/.next/server/chunks/ssr/_0pbav_w._.js +3 -0
- package/.next/server/chunks/ssr/{_0vo_oym._.js → _0q-mdwv._.js} +8 -8
- package/.next/server/chunks/ssr/_0s5_ahb._.js +3 -0
- package/.next/server/chunks/ssr/{_0e2fnvg._.js → _0t5f2c3._.js} +2 -2
- package/.next/server/chunks/ssr/_0v9r8g2._.js +1 -1
- package/.next/server/chunks/ssr/_0x8ophf._.js +1 -1
- package/.next/server/chunks/ssr/_0x9f717._.js +60 -0
- package/.next/server/chunks/ssr/_107vtdk._.js +162 -0
- package/.next/server/chunks/ssr/{_17a4qyk._.js → _12lql1x._.js} +3 -3
- package/.next/server/chunks/ssr/{_163dr78._.js → _165wnr4._.js} +2 -2
- package/.next/server/chunks/ssr/_16_7zeo._.js +3 -0
- package/.next/server/chunks/ssr/_17komoi._.js +3 -0
- package/.next/server/chunks/ssr/_190hjys._.js +3 -0
- package/.next/server/chunks/ssr/_1bfrntd._.js +6 -0
- package/.next/server/chunks/ssr/{_01al00i._.js → _1booff4._.js} +2 -2
- package/.next/server/chunks/ssr/{_0xfafez._.js → _1ew1j7l._.js} +2 -2
- package/.next/server/chunks/ssr/_1i2swyr._.js +3 -0
- package/.next/server/chunks/ssr/_1neoj22._.js +1 -1
- package/.next/server/chunks/ssr/_1qsa25k._.js +3 -0
- package/.next/server/chunks/ssr/_1soynbw._.js +6 -0
- package/.next/server/chunks/ssr/_1vc2xmu._.js +3 -0
- package/.next/server/chunks/ssr/{_14oirtb._.js → _1wq90j8._.js} +2 -2
- package/.next/server/chunks/ssr/_1xwtbdz._.js +3 -0
- package/.next/server/chunks/ssr/_1zrhkf0._.js +310 -0
- package/.next/server/chunks/ssr/_21awrs2._.js +5 -0
- package/.next/server/chunks/ssr/features_0796o8r._.js +1 -1
- package/.next/server/chunks/ssr/features_bot_0tb4ui-._.js +2 -2
- package/.next/server/chunks/ssr/features_bot_1c56lew._.js +37 -0
- package/.next/server/chunks/ssr/features_bot_1fn_grf._.js +3 -0
- package/.next/server/chunks/ssr/{features_config_09n-q9q._.js → features_config_05zi68v._.js} +3 -3
- package/.next/server/chunks/ssr/features_connectors_components_mcp-setting_tsx_0jmbgvp._.js +1 -1
- package/.next/server/chunks/ssr/features_memory_components_memory-setting_tsx_0oa43sw._.js +1 -1
- package/.next/server/chunks/ssr/features_routine_components_routine-setting_tsx_055fknz._.js +1 -1
- package/.next/server/chunks/ssr/features_workspace_workspace_ts_1wc7_u_._.js +4 -4
- package/.next/server/chunks/ssr/{node_modules_1k5i-_9._.js → node_modules_0-sux1a._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0msrhxf._.js → node_modules_01oezhb._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1gq3ght._.js → node_modules_04m6ebg._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0nmkv-v._.js → node_modules_067jfov._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0gd9hbz._.js → node_modules_06ugby3._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0d6j33x._.js → node_modules_07p51j3._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_10_fv2a._.js → node_modules_0995xyq._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1lmyts8._.js → node_modules_0_uecwx._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_04x5wyv._.js → node_modules_0dsyc90._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0__0tvm._.js → node_modules_0hli6s2._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0k8-y89._.js → node_modules_0m-bde_._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1p_6sq7._.js → node_modules_0oqfdbr._.js} +1 -1
- package/.next/server/chunks/ssr/node_modules_0qd7p5f._.js +3 -0
- package/.next/server/chunks/ssr/{node_modules_13g-d25._.js → node_modules_0tgy5s5._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1_8-jcj._.js → node_modules_1-kjmls._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0m73b88._.js → node_modules_1-l3ka5._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_113l3e5._.js → node_modules_1-w3ayh._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0q-klni._.js → node_modules_133exgm._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1xb-ndg._.js → node_modules_17xc5_k._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_021lid9._.js → node_modules_1_i_w30._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1ri_eip._.js → node_modules_1a2cjfk._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_13bqv6i._.js → node_modules_1k752fe._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1qstb1x._.js → node_modules_1lie7z8._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_096up6a._.js → node_modules_1mv70-y._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_156kv_t._.js → node_modules_1r611t2._.js} +1 -1
- package/.next/server/chunks/ssr/node_modules_1vfd8dz._.js +3 -0
- package/.next/server/chunks/ssr/{node_modules_0cjnmzp._.js → node_modules_1yaowd7._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0nw5jz7._.js → node_modules_20a1wpo._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0amkw0b._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1r8pxbe._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0zq3l45._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1siiu4h._.js} +1 -1
- package/.next/server/middleware-build-manifest.js +3 -3
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.js +1 -1
- package/.next/server/server-reference-manifest.json +205 -132
- package/.next/static/chunks/{0obogzscwwekj.js → 088d3w5qxu19g.js} +2 -2
- package/.next/static/chunks/0_s4z70lx1tgs.js +1 -0
- package/.next/static/chunks/0bxekp4hnuk1g.js +1 -0
- package/.next/static/chunks/{1cglo3a2mbeou.js → 0fw4u_s974j24.js} +1 -1
- package/.next/static/chunks/0hy2x7qhk8wgx.css +1 -0
- package/.next/static/chunks/{2zbl41hed17g3.js → 0n_eshmn_7wfn.js} +2 -2
- package/.next/static/chunks/0q9b2n6l4flqb.js +1 -0
- package/.next/static/chunks/0ulcp_u_y1u0b.js +15 -0
- package/.next/static/chunks/0vj93zo0yvix9.js +35 -0
- package/.next/static/chunks/{166smhw8v-s3j.js → 10f98bh4hdmhe.js} +1 -1
- package/.next/static/chunks/1b8bce_z_act0.js +1 -0
- package/.next/static/chunks/1c32d2azsjaj_.js +1 -0
- package/.next/static/chunks/{1xv4g10m-cl1s.js → 1fs829mz69pxz.js} +1 -1
- package/.next/static/chunks/1lwlh4mo_vv8d.js +1 -0
- package/.next/static/chunks/{0p2f6uv4xytfm.js → 1po8fkg40peu-.js} +1 -1
- package/.next/static/chunks/{0uxq_vs6uxi-b.js → 1rg6b9l5fm1hj.js} +1 -1
- package/.next/static/chunks/{3b96xy59nl_gd.js → 26g3iwfuad-7p.js} +1 -1
- package/.next/static/chunks/2bjnmtke_q43c.js +1 -0
- package/.next/static/chunks/2c86k0o-1p9_w.js +1 -0
- package/.next/static/chunks/2gf4t0d76bvyv.js +1 -0
- package/.next/static/chunks/2rj3q_ahctv19.js +1 -0
- package/.next/static/chunks/{2lhc74urf3acr.js → 2x6-fpctvucte.js} +1 -1
- package/.next/static/chunks/2yicf7bky866n.js +3 -0
- package/.next/static/chunks/337g9g_ux2gj-.js +1 -0
- package/.next/static/chunks/350ws7svim7ij.js +58 -0
- package/.next/static/chunks/{0o7o0eb7ihxi6.js → 396enq-m0sss5.js} +1 -1
- package/.next/static/chunks/3e1w_nwfb39j-.js +1 -0
- package/.next/static/chunks/3v3ooretb54ag.js +1 -0
- package/.next/static/chunks/40re_3ukjulg9.js +1 -0
- package/.next/static/chunks/{3gsxnqqqphh-1.js → 44bcbnmup71so.js} +1 -1
- package/.next/static/chunks/{2qgkbdshzpq1c.js → 458dtbsemx996.js} +1 -1
- package/README.md +5 -5
- package/bin/background.mjs +995 -0
- package/bin/lock.mjs +121 -5
- package/bin/thursday.mjs +126 -30
- package/bin/tools.mjs +72 -1
- package/database/migrations/20260926021847_thread_cache_tokens/migration.sql +2 -0
- package/database/migrations/20260926021847_thread_cache_tokens/snapshot.json +1949 -0
- package/guide/bots.md +173 -317
- package/guide/calls.md +106 -146
- package/guide/index.md +2 -2
- package/guide/memory.md +14 -18
- package/guide/phone.md +86 -133
- package/guide/setup.md +141 -172
- package/guide/trouble.md +42 -65
- package/package.json +1 -1
- package/seed-skills/concierge/travel/references/itinerary.md +1 -1
- package/seed-skills/concierge/travel/scripts/itinerary.mjs +8 -3
- package/skills/artifact/references/book.md +3 -3
- package/skills/artifact/runtime/shell/shell.js +32 -3
- package/.next/server/app/api/llm-model/catalog/route/app-paths-manifest.json +0 -3
- package/.next/server/app/api/llm-model/catalog/route.js.nft.json +0 -1
- package/.next/server/app/api/llm-model/catalog/route_client-reference-manifest.js +0 -3
- package/.next/server/app/api/llm-model/credits/route/app-paths-manifest.json +0 -3
- package/.next/server/app/api/llm-model/credits/route.js.nft.json +0 -1
- package/.next/server/app/api/llm-model/credits/route_client-reference-manifest.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__01ypm_z._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__021dkui._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__03xamry._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__09gdscj._.js +0 -7
- package/.next/server/chunks/[root-of-the-server]__0ljizgj._.js +0 -5
- package/.next/server/chunks/[root-of-the-server]__0nmust6._.js +0 -5
- package/.next/server/chunks/[root-of-the-server]__0svzjwa._.js +0 -7
- package/.next/server/chunks/[root-of-the-server]__1-rmal0._.js +0 -5
- package/.next/server/chunks/[root-of-the-server]__10xnb7e._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1_h4hf9._.js +0 -7
- package/.next/server/chunks/[root-of-the-server]__1c2kwku._.js +0 -12
- package/.next/server/chunks/[root-of-the-server]__1t02-1p._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1t0jj1j._.js +0 -5
- package/.next/server/chunks/[root-of-the-server]__1v7x5ym._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1vlxv19._.js +0 -5
- package/.next/server/chunks/_07nxi75._.js +0 -254
- package/.next/server/chunks/_08btiir._.js +0 -7
- package/.next/server/chunks/_0j0-gq6._.js +0 -5
- package/.next/server/chunks/_0p6v1fr._.js +0 -5
- package/.next/server/chunks/_0srlnvd._.js +0 -16
- package/.next/server/chunks/_0xygcxs._.js +0 -254
- package/.next/server/chunks/_1ic3bew._.js +0 -5
- package/.next/server/chunks/_next-internal_server_app_api_llm-model_catalog_route_actions_1eu2y41.js +0 -3
- package/.next/server/chunks/_next-internal_server_app_api_llm-model_credits_route_actions_0v424pb.js +0 -3
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_04oxl25._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0-af_o7._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__09f39cp._.js +0 -4
- package/.next/server/chunks/ssr/[root-of-the-server]__0ouu4qp._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0q9g9ea._.js +0 -5
- package/.next/server/chunks/ssr/[root-of-the-server]__17h1ggo._.js +0 -46
- package/.next/server/chunks/ssr/[root-of-the-server]__1jyeu61._.js +0 -5
- package/.next/server/chunks/ssr/_0afrpci._.js +0 -3
- package/.next/server/chunks/ssr/_0bgse1c._.js +0 -162
- package/.next/server/chunks/ssr/_0jstvlg._.js +0 -39
- package/.next/server/chunks/ssr/_0qsmpcu._.js +0 -3
- package/.next/server/chunks/ssr/_0z38nha._.js +0 -3
- package/.next/server/chunks/ssr/_1-41lck._.js +0 -3
- package/.next/server/chunks/ssr/_10_ph1t._.js +0 -3
- package/.next/server/chunks/ssr/_116lfdc._.js +0 -3
- package/.next/server/chunks/ssr/_14dfh7a._.js +0 -4
- package/.next/server/chunks/ssr/_17qtuv7._.js +0 -3
- package/.next/server/chunks/ssr/_19jez1a._.js +0 -3
- package/.next/server/chunks/ssr/_1_5xof_._.js +0 -3
- package/.next/server/chunks/ssr/_1alxym6._.js +0 -3
- package/.next/server/chunks/ssr/_1ou5sj0._.js +0 -3
- package/.next/server/chunks/ssr/_1tmw842._.js +0 -5
- package/.next/server/chunks/ssr/_1uij_rj._.js +0 -3
- package/.next/server/chunks/ssr/_1w9w1ok._.js +0 -3
- package/.next/server/chunks/ssr/_20gq_24._.js +0 -3
- package/.next/server/chunks/ssr/features_bot_0ouemw8._.js +0 -3
- package/.next/server/chunks/ssr/node_modules_@base-ui_react_1j9i1ho._.js +0 -3
- package/.next/static/chunks/01l7kw74vfp32.js +0 -1
- package/.next/static/chunks/0a5_-jqhaktjj.js +0 -1
- package/.next/static/chunks/0npvak0wpgagb.js +0 -1
- package/.next/static/chunks/19l81deo_pyoc.js +0 -1
- package/.next/static/chunks/1bnhw-5fj7aiz.js +0 -1
- package/.next/static/chunks/1in6nxpu33iab.js +0 -1
- package/.next/static/chunks/1u7kg91f9qy3g.js +0 -1
- package/.next/static/chunks/2ajs12-fcdwzm.js +0 -1
- package/.next/static/chunks/2i7qtmxc1kuqg.js +0 -1
- package/.next/static/chunks/2kz1f6r59nky0.js +0 -3
- package/.next/static/chunks/31kn4_h2rvf6k.css +0 -1
- package/.next/static/chunks/35jj-5u4te56r.js +0 -1
- package/.next/static/chunks/37ixzapa06xlo.js +0 -1
- package/.next/static/chunks/3jtcieuk1l6tw.js +0 -1
- package/.next/static/chunks/3k1d8y03t5nax.js +0 -58
- package/.next/static/chunks/3sla-dm1puqd1.js +0 -35
- package/.next/static/chunks/3t2c76awm9k_p.js +0 -1
- package/.next/static/chunks/3vrmcm31ih7gb.js +0 -1
- package/.next/static/chunks/3yiqr95d7ybeq.js +0 -15
- package/bin/autostart.mjs +0 -162
- /package/.next/server/app/api/{llm-model/catalog → bot/thread/file}/route/build-manifest.json +0 -0
- /package/.next/server/app/api/{llm-model/catalog → bot/thread/file}/route/server-reference-manifest.json +0 -0
- /package/.next/server/app/api/{llm-model/catalog → bot/thread/file}/route.js.map +0 -0
- /package/.next/server/app/api/llm-model/{credits → catalog/[provider]}/route/build-manifest.json +0 -0
- /package/.next/server/app/api/llm-model/{credits → catalog/[provider]}/route/server-reference-manifest.json +0 -0
- /package/.next/server/app/api/llm-model/{credits → catalog/[provider]}/route.js.map +0 -0
- /package/.next/static/{8I2hKtciyA9LXvd8txuOz → YhaRHJqObuAcXZe5VLFs0}/_buildManifest.js +0 -0
- /package/.next/static/{8I2hKtciyA9LXvd8txuOz → YhaRHJqObuAcXZe5VLFs0}/_clientMiddlewareManifest.js +0 -0
- /package/.next/static/{8I2hKtciyA9LXvd8txuOz → YhaRHJqObuAcXZe5VLFs0}/_ssgManifest.js +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
module.exports=[652619,a=>a.a(async(b,c)=>{try{var d=a.i(666680),e=a.i(347299),f=a.i(345364),g=a.i(47919),h=a.i(868468),i=a.i(53112),j=a.i(569572),k=a.i(725466),l=a.i(176668),m=a.i(523095),n=a.i(293480),o=a.i(8412),p=a.i(182248),q=a.i(689656),r=b([k]);[k]=r.then?(await r)():r;let C="app_EMoamEEZ73f0CkXaXp7hrann",D="http://localhost:1455/auth/callback",E=["127.0.0.1","::1"],F="thursday",{apiKeyName:G,label:H}=q.TEXT_MODEL_PROVIDERS.chatgpt,I=`${H} is not signed in — sign in from Settings › API keys.`,J=i.z.object({access:i.z.string().min(1),refresh:i.z.string().min(1),expires:i.z.number(),accountId:i.z.string().min(1),plan:i.z.string().nullable()}),K=globalThis,L=K.__chatgptRenewal??=(0,o.createKeyedLock)();async function s(){t();let a=(0,d.randomBytes)(32).toString("base64url"),b=(0,d.randomBytes)(16).toString("hex"),c=[],f=(d,e)=>{u(d.url??"/",{state:b,verifier:a}).then(a=>{e.writeHead(a.status,{"content-type":"text/html; charset=utf-8"}),e.end((0,m.oauthPage)(a.title,a.detail,{autoClose:200===a.status}),()=>{a.last&&K.__chatgptListeners===c&&t()})})};for(let a of E){let b=(0,e.createServer)(f),d=await new Promise(c=>{b.once("error",c),b.listen(1455,a,()=>c(null))});if(!d){c.push(b);continue}if("EADDRNOTAVAIL"!==d.code&&"EAFNOSUPPORT"!==d.code){for(let a of c)a.close();(0,n.publicError)("EADDRINUSE"===d.code?"Port 1455 is in use by another app — often a ChatGPT or Codex sign-in still waiting. Finish or close it, then try again.":`Could not wait for the sign-in: ${(0,p.errorToString)(d)}`)}}K.__chatgptListeners=c,setTimeout(()=>{K.__chatgptListeners===c&&t()},j.CHATGPT_SIGN_IN.waitMs).unref();let g=new URL("https://auth.openai.com/oauth/authorize");return g.search=new URLSearchParams({response_type:"code",client_id:C,redirect_uri:D,scope:"openid profile email offline_access",code_challenge:(0,d.createHash)("sha256").update(a).digest("base64url"),code_challenge_method:"S256",state:b,id_token_add_organizations:"true",codex_cli_simplified_flow:"true",originator:F}).toString(),g.toString()}function t(){let a=K.__chatgptListeners;for(let b of(K.__chatgptListeners=null,a??[]))b.close(),b.closeIdleConnections()}async function u(a,b){let c=new URL(a,D);if("/auth/callback"!==c.pathname)return{status:404,title:"Not found",detail:"",last:!1};let d=c.searchParams.get("error");if(d){let a=c.searchParams.get("error_description");return{status:400,title:"Sign-in failed",detail:a?`${d}: ${a}`:d,last:!0}}let e=c.searchParams.get("code");if(!e||c.searchParams.get("state")!==b.state)return{status:400,title:"Sign-in failed",detail:"This is not the sign-in that was started. Start again from Settings › API keys.",last:!1};try{let a=await v({grant_type:"authorization_code",code:e,code_verifier:b.verifier,redirect_uri:D});return await (0,k.writeConfig)(G,JSON.stringify(a)),{status:200,title:"Signed in to ChatGPT",detail:"Bots can run on your plan now. This window closes itself.",last:!0}}catch(a){return l.logger.warn({cause:a},"chatgpt sign-in failed"),{status:502,title:"Sign-in failed",detail:(0,p.errorToString)(a),last:!0}}}async function v(a){let b=await fetch("https://auth.openai.com/oauth/token",{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:C,...a})}).catch(a=>{l.logger.warn({cause:a},"chatgpt token endpoint unreachable"),(0,n.publicError)("Could not reach ChatGPT's sign-in")}),c=await b.json().catch(()=>null),d=c?.access_token;if(!b.ok||!d){let a=c?.error,d="string"==typeof a?[a,c?.error_description].filter(Boolean).join(": "):a?.message??a?.code??"";(0,n.publicError)(`ChatGPT's sign-in answered ${b.status}${d?`: ${d}`:""}`)}let e=function(a){try{let b=JSON.parse(Buffer.from(a.split(".")[1]??"","base64url").toString("utf8")),c=b["https://api.openai.com/auth"]??{};return{accountId:"string"==typeof c.chatgpt_account_id?c.chatgpt_account_id:null,plan:"string"==typeof c.chatgpt_plan_type?c.chatgpt_plan_type:null,expires:"number"==typeof b.exp?1e3*b.exp:null}}catch{return{accountId:null,plan:null,expires:null}}}(d),f=c?.refresh_token??a.refresh_token;e.accountId&&f||(0,n.publicError)("ChatGPT's sign-in came back without an account");let g=c?.expires_in;return{access:d,refresh:f,expires:"number"==typeof g?Date.now()+1e3*g:e.expires??Date.now(),accountId:e.accountId,plan:e.plan}}async function w(){let a=await (0,k.readConfig)(G);if(!a)return null;try{return J.parse(JSON.parse(a))}catch{return null}}let M=a=>a.expires-j.CHATGPT_SIGN_IN.renewBeforeMs<=Date.now();async function x(){let a=await w();return(a||(0,n.publicError)(I),M(a))?L(G,async()=>{let a=await w();if(a||(0,n.publicError)(I),!M(a))return a;try{let b=await v({grant_type:"refresh_token",refresh_token:a.refresh});return await (0,k.writeConfig)(G,JSON.stringify(b)),b}catch(a){(0,n.publicError)(`Could not renew the ${H} sign-in (${(0,p.errorToString)(a)}). If it keeps failing, sign in again from Settings › API keys.`)}}):a}async function y(){return(await w())?.plan??null}async function z(a,b){let c=await x(),d=new Headers(b?.headers);if(d.set("authorization",`Bearer ${c.access}`),d.set("chatgpt-account-id",c.accountId),d.set("originator",F),b?.method!=="POST"||"string"!=typeof b.body||!String(a).endsWith("/responses"))return fetch(a,{...b,headers:d});let e=JSON.parse(b.body),f=!0===e.stream,g=[];e.input=(e.input??[]).filter(a=>"system"!==a.role&&"developer"!==a.role||(g.push("string"==typeof a.content?a.content:(a.content??[]).map(a=>a.text??"").join("\n")),!1)),e.instructions=[e.instructions,...g].filter(Boolean).join("\n\n")||"You are a helpful assistant.",e.store=!1,e.stream=!0,e.max_output_tokens=void 0,d.set("accept","text/event-stream");let h=await fetch(a,{...b,headers:d,body:JSON.stringify(e)});return 429===h.status?A(h):f||!h.ok?h:B(h)}async function A(a){let b=await a.text(),c={};try{c=JSON.parse(b).error??{}}catch{}if(!/usage_limit_reached|usage_not_included/.test(`${c.code} ${c.type}`)){let c=a.headers.get("retry-after");return new Response(b,{status:429,headers:{"content-type":"application/json",...c?{"retry-after":c}:{}}})}let d=c.resets_at?1e3*c.resets_at:c.resets_in_seconds?Date.now()+1e3*c.resets_in_seconds:null,e=c.plan_type?` on the ${c.plan_type} plan`:"",f=d?` It resets in ${(0,h.formatDistanceToNowStrict)(d)}.`:"";return Response.json({error:{message:`${H} usage limit reached${e}.${f}`,code:c.code??c.type}},{status:402})}async function B(a){let b=[],c=null,d=null;for(let e of(await a.text()).replaceAll("\r\n","\n").split("\n\n")){let a,f=e.split("\n").filter(a=>a.startsWith("data:")).map(a=>a.slice(5).trimStart()).join("\n");if(f&&"[DONE]"!==f){try{a=JSON.parse(f)}catch{continue}"response.output_item.done"===a.type?b.push(a.item):"response.completed"===a.type||"response.incomplete"===a.type?c=a.response??{}:"response.failed"===a.type?d=a.response?.error??{message:"The response failed"}:"error"===a.type&&(d={code:a.code,message:a.message})}}return d||!c?Response.json({error:{message:d?.message??"The stream ended before the response finished",code:d?.code}},{status:d?.code==="context_length_exceeded"?400:500}):Response.json({...c,output:c.output?.length?c.output:b})}a.s(["chatGptModel",0,function(a){let b=(0,f.createOpenAI)({baseURL:"https://chatgpt.com/backend-api/codex",apiKey:"signed-in",headers:{"OpenAI-Beta":"responses=experimental"},fetch:z}),c=(0,d.randomUUID)();return(0,g.wrapLanguageModel)({model:b.responses(a),middleware:{transformParams:async({params:a})=>({...a,providerOptions:{...a.providerOptions,openai:{promptCacheKey:c,...a.providerOptions?.openai,store:!1,includeWebSearchSources:!1}}})}})},"chatGptSearch",0,()=>(0,f.createOpenAI)({apiKey:"signed-in"}).tools.webSearch(),"readChatGptPlan",0,y,"startChatGptSignIn",0,s]),c()}catch(a){c(a)}},!1),884780,a=>{"use strict";a.i(902157),a.i(912714);var b=a.i(750227),c=a.i(569572);(0,b.join)(c.APP_DIR,"guide");let d=".guide";a.s(["botGuideLine",0,()=>`How ${c.APP_NAME} itself works for the user — its screens and settings — is written under \`${d}/\` here, \`index.md\` first; read it only when the job is about the app.`,"guideLine",0,()=>`How ${c.APP_NAME} works for the person using it — its screens, its settings, what it connects to, what to do when something stops — is written under \`${d}/\` here, \`index.md\` first. Read it whenever an answer depends on how the app works: what can be asked for, where something is changed, a wish that needs a setting switched on, something that stopped or was refused. Answer from it rather than from what you assume.`])},738131,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(868468),f=a.i(569572),g=a.i(875931),h=a.i(938934),i=a.i(978876),j=a.i(375827),k=a.i(127507),l=a.i(467650),m=a.i(138902),n=a.i(345846),o=a.i(617594),p=a.i(622547),q=a.i(128232),r=a.i(382442),s=a.i(451017),t=a.i(762008),u=a.i(547613),v=a.i(446957),w=a.i(138100),x=a.i(821415),y=a.i(706210),z=a.i(176668),A=a.i(293480),B=a.i(987674),C=a.i(182248),D=b([g,i,m,n,o,p,q,s,w]);async function E(b){let{listThreadOverview:c}=await a.A(343064),d=await c();if(!d.length)return"No thread has been started yet.";let e=d.map(a=>`"${a.label}" (${a.bot}, ${a.status})`).join(", ");return`There is no thread called "${b}". The latest are: ${e}. Call again with one of those labels.`}async function F(a,b){let c=[];for(let[a,e]of Object.entries(b)){let b=await (0,d.asSchema)(e.inputSchema).jsonSchema,f="string"==typeof e.description?e.description:"";c.push({name:a,tokens:(0,B.estimateTokens)(f)+(0,B.estimateTokens)(JSON.stringify(b))})}c.sort((a,b)=>b.tokens-a.tokens);let e=c.reduce((a,b)=>a+b.tokens,0);z.logger.debug(`${a} tools ${e} tokens over ${c.length} — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`)}async function G(a){let b=await H(a);return f.IS_DEV&&await F(a.target,b),b}async function H(b){if("memory-edit"===b.target)return(0,n.createMemoryTools)("user",null,{countReads:!1});let c=(0,n.createMemoryTools)("call","thursday"===b.target?b.callId??null:null),z=await (0,x.openWorkspace)();if("thursday"===b.target){var B;let k,m,n=b.readSkills?(0,s.createSkillTools)({sandbox:z,skills:await (0,w.loadSkills)(z)}):{},q=!!(b.written&&b.model&&(0,g.seesToolImages)(b.model));return{...c,...n,...(0,u.createWorkspaceTools)(z,{write:!1,timeoutMs:f.CALL_EXEC_TIMEOUT_MS}),...!1===b.webSearch?{}:await (0,p.createCallSearchTool)(z),...Object.fromEntries(Object.entries((B=b.callId,k=async b=>{let{resolveThread:c}=await a.A(343064);return(b.trim()?await c(b.trim()):null)??await E(b)},m=async(b,c,d)=>{let e=await a.A(763543);try{return await e.answerThread(b,c,"thursday",d)}catch(a){if((0,A.isPublicError)(a))return a.message;throw a}},{[t.TOOL_NAMES.thread_start]:(0,d.tool)({description:i.threadStartSpec.description,inputSchema:i.threadStartSpec.parameters,execute:async({bot:b,request:c,label:d})=>{let{findJobBot:e,listJobBots:f}=await a.A(276307),g=await e(b);if(!g||g.disabled){let a=(await f()).map(a=>a.name);return`There is no bot called "${b}". The bots are: ${a.join(", ")}. Nothing was started — call again with one of those.`}let{startThread:h}=await a.A(763543);return{threadId:await h({bot:g.name,request:c,label:d,callId:B,from:"thursday"}),bot:g.name,label:d,note:`${g.name} has "${d}". Its updates reach the conversation on their own. Anything further about this work — a correction, the next step once it finishes — is \`${t.TOOL_NAMES.thread_tell}\` with "${d}"; a question it asks is answered with \`${t.TOOL_NAMES.thread_answer}\`.`}}}),[t.TOOL_NAMES.thread_tell]:(0,d.tool)({description:i.threadTellSpec.description,inputSchema:i.threadTellSpec.parameters,execute:async({thread:a,words:b})=>{let c=await k(a);if("string"==typeof c)return c;if(!b.trim())return"Say what to pass on.";let d=await m(c.id,b.trim());return"string"==typeof d?d:d?.answered?{label:c.label,answered:d.answered,note:`${d.answered.bot} was waiting on a question, and took this as its answer.`}:{label:c.label,bot:d?.to??c.bot,status:"running",note:"running"===c.status?"The bot reads it before its next step.":"The bot picks the thread back up from there."}}}),[t.TOOL_NAMES.thread_answer]:(0,d.tool)({description:i.threadAnswerSpec.description,inputSchema:i.threadAnswerSpec.parameters,execute:async({thread:b,bot:c,answer:d})=>{let e=await k(b);if("string"==typeof e)return e;if(!d.trim())return"Say what the answer is.";let{findThreadView:f}=await a.A(343064),g=(await f(e.id))?.room.questions??[],h=g.find(a=>a.bot.toLowerCase()===c.trim().toLowerCase());if(!h)return g.length?`${c} is not asking anything in "${e.label}". Waiting there: ${g.map(a=>a.bot).join(", ")}. Call again with that bot.`:`No question is waiting in "${e.label}". To say something else to it, use \`${t.TOOL_NAMES.thread_tell}\`.`;let i=await m(e.id,d.trim(),h.bot);return"string"==typeof i?i:{label:e.label,answered:i?.answered??{bot:h.bot,question:h.text},note:`${h.bot} has the answer to its question and goes on from it.`}}}),[t.TOOL_NAMES.thread_status]:(0,d.tool)({description:i.threadStatusSpec.description,inputSchema:i.threadStatusSpec.parameters,execute:async({thread:b})=>{let{listThreadOverview:c,findThreadView:d}=await a.A(343064),g={now:(0,h.clockNow)()},i=a=>(0,e.formatDistanceToNowStrict)((0,y.toDate)(a),{addSuffix:!0});if(!(!b.trim()||"all"===b.trim().toLowerCase())){let a=await k(b);if("string"==typeof a)return a;let c=(await d(a.id))?.room;return{...g,label:a.label,id:a.id,bot:a.bot,participants:c?.participants??[],questions:c?.questions??[],status:a.status,since:i(a.updatedAt),outcome:a.outcome,..."waiting"===a.status&&a.pending?.options.length?{options:a.pending.options}:{}}}let j=await c();return j.length?{...g,threads:j.map(a=>({id:a.id,label:a.label,bot:a.bot,status:a.status,participants:a.room.participants,questions:a.room.questions.map(a=>({...a,text:(0,C.clip)(a.text,f.PROMPT_LINE.threadStatus)})),since:i(a.updatedAt),...a.ask?{asking:a.ask.question,options:a.ask.options}:{},..."running"===a.status?{now:(0,v.threadActivity)(a.lines)}:{},...a.outcome&&"waiting"!==a.status?{outcome:(0,C.clip)(a.outcome,f.PROMPT_LINE.threadStatus)}:{}}))}:"No thread has been started yet."}}),[t.TOOL_NAMES.thread_cancel]:(0,d.tool)({description:i.threadCancelSpec.description,inputSchema:i.threadCancelSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{cancelThread:d}=await a.A(763543);return await d(c.id),{label:c.label,status:"cancelled"}}}),[t.TOOL_NAMES.thread_show]:(0,d.tool)({description:i.threadShowSpec.description,inputSchema:i.threadShowSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{appEvents:d}=await a.A(133300),{filesOnDisk:e}=await a.A(122690),{leadFirst:f,pathsIn:g,viewKindOf:h}=await a.A(394298),i=(await e(g(c.outcome??""),null)).filter(a=>"none"!==h(a));if(!i.length)return d.emit({type:"showThread",threadId:c.id}),{label:c.label,showing:"the thread"};let j=f(i);d.emit({type:"showFile",paths:j});let{markSeen:l}=await a.A(343064);return await l([c.id]),{label:c.label,showing:j[0]}}}),[t.TOOL_NAMES.thread_seen]:(0,d.tool)({description:i.threadSeenSpec.description,inputSchema:i.threadSeenSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{markSeen:d}=await a.A(343064);return await d([c.id]),{label:c.label,seen:!0}}})})).filter(([a])=>!(b.phone&&a===t.TOOL_NAMES.thread_show))),...(0,o.createRoutineTools)(),...q?(0,l.createLookTool)():{},...b.written?{}:(0,j.callTools)()}}let D=await (0,w.loadSkills)(z,b.bot),F={...(0,x.jobShellEnv)(b.session),...(0,x.botShellEnv)(b.bot,(await (await a.A(276307)).findJobBot(b.bot))?.icon)},G=!!(b.model&&(0,g.seesToolImages)(b.model.ref));return{[t.TOOL_NAMES.memory_recall]:(0,n.createMemoryTools)("call",null,{tidies:!1})[t.TOOL_NAMES.memory_recall],...await (0,p.createSearchTool)(b.model,z),...(0,u.createWorkspaceTools)(z,{write:!0,env:F,guide:!0,bot:b.bot}),...await (0,m.createMcpTools)(b.bot,z),...(0,s.createSkillTools)({sandbox:z,skills:D,bot:b.bot}),...await (0,q.createSelfTools)(b.bot),...(0,k.createDeckTools)(z,b.bot,F,G),...G?(0,l.createLookTool)():{},...(0,r.createSignInTools)(z,b.bot,(0,x.jobShellEnv)(b.session)),...await (0,i.createThreadRecallTool)(b.bot,b.thread??null)}}[g,i,m,n,o,p,q,s,w]=D.then?(await D)():D,a.s(["loadTools",0,G]),c()}catch(a){c(a)}},!1),875931,a=>a.a(async(b,c)=>{try{var d=a.i(938537),e=a.i(674861),f=a.i(606016),g=a.i(388319),h=a.i(538177),i=a.i(767071),j=a.i(140358),k=a.i(873739),l=a.i(899042),m=a.i(345364),n=a.i(434451),o=a.i(655819),p=a.i(652685),q=a.i(156956),r=a.i(47919),s=a.i(569572),t=a.i(688034),u=a.i(725466),v=a.i(176668),w=a.i(293480),x=a.i(182248),y=a.i(652619),z=a.i(689656),A=b([u,y]);[u,y]=A.then?(await A)():A;let N=/context[ _-]?(length|window)|maximum context|prompt is too long|too many (input )?tokens|input token count|exceeds? the (maximum|model'?s?) (context|input|prompt|number of tokens)|maximum prompt length|request (entity )?too large/i;function B(a){return C(a).some(a=>{let{statusCode:b,message:c,error:d}=a;if(void 0!==b&&400!==b&&413!==b)return!1;let e=p.APICallError.isInstance(a)?a.responseBody:null;return[c,d,e].some(a=>"string"==typeof a&&N.test(a))})}let O=new Set([408,409,429]);function C(a){let b=[],c=[a];for(;c.length&&b.length<12;){let a=c.shift();!("object"!=typeof a||null===a||b.includes(a))&&(b.push(a),r.RetryError.isInstance(a)&&c.push(...a.errors),"cause"in a&&c.push(a.cause))}return b}let P=(a,b)=>({ref:a,model:b,searchTools:null}),Q=null;function D(a){if(null==a||""===a)return null;let b=Number(a);return Number.isFinite(b)?Math.round(1e6*b*1e4)/1e4:null}async function E(){if(Q&&Date.now()-Q.at<s.GATEWAY_CATALOG_MS)return Q.models;let a=await fetch("https://ai-gateway.vercel.sh/v1/models",{headers:{accept:"application/json"}}).catch(a=>{v.logger.warn({cause:a},"gateway catalog unreachable"),(0,w.publicError)("Could not reach the gateway")});a.ok||(0,w.publicError)(`The gateway answered ${a.status}`);let b=((await a.json()).data??[]).filter(a=>!!a.id).map(a=>{let b,c;return{id:a.id,label:a.name||a.id,owner:a.owned_by||a.id.slice(0,a.id.indexOf("/")),type:a.type??null,tags:a.tags??[],price:function(a){let b=a.pricing??{},c=D(b.input),d=D(b.output);if((a.tags??[]).includes("free")||0===c)return{in:0,out:0,note:null,free:!0};let e=b.transcription_duration_cost_per_second??b.realtime_session_duration_cost_per_second;if(e)return{in:null,out:null,note:`$${e}/s`,free:!1};if(b.speech_input_character_cost)return{in:null,out:null,note:"per character",free:!1};let f=Array.isArray(b.video_duration_pricing)?b.video_duration_pricing[0]:null;if(f?.cost_per_second)return{in:null,out:null,note:`$${f.cost_per_second}/s ${f.resolution??""}`.trimEnd(),free:!1};let g=b.image?`$${b.image}/image`:b.image_dimension_quality_pricing?"per image, by size":null;return null===c&&null===d?{in:null,out:null,note:g,free:!1}:{in:c,out:d,note:b.input_tiers?"tiered":b.varies_by_provider?"varies":g&&"+ per image",free:!1}}(a),retiring:!!a.deprecated_at,contextWindow:"number"==typeof a.context_window&&a.context_window>0?a.context_window:null,efforts:(b=(a.reasoning_options??[]).find(a=>a?.type==="effort"),(c=z.EFFORTS.filter(a=>b?.values?.includes(a))).length?c:null)}}).sort((a,b)=>a.id.localeCompare(b.id));return Q={at:Date.now(),models:b},b}async function F(a,b){if(b&&b>0)return b;let c=await G(a);return(0,z.compactAtFor)((0,z.contextWindowOf)(a.provider,a.model,c))}async function G(a){return"vercel-ai-gateway"!==a.provider?[]:await E().catch(()=>[])}async function H(a,b){let c=b??z.effortSchema.safeParse(await (0,u.readConfig)(t.DEFAULT_EFFORT_KEY)).data;if(!c)return;let d=await G(a);return(0,z.effortsOf)(a.provider,a.model,d)?.includes(c)?c:void 0}async function I(){return await E().then(a=>new Set(a.map(a=>a.id))).catch(()=>null)}async function J(a,b){if("vercel-ai-gateway"!==a)return b;let c=await I();if(!c)return b;let d=b.filter(a=>c.has(a.id));return d.length>0?d:b}async function K(a){let{label:b,apiKeyName:c,signIn:p}=z.TEXT_MODEL_PROVIDERS[a.provider],r=await (0,u.readConfig)(c);return r||(0,w.publicError)(p?`${b} is not signed in — sign in from Settings › API keys.`:`No ${b} key — add one in Settings › API keys.`),function(a,b){switch(a.provider){case"openai":{let c=(0,m.createOpenAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"chatgpt":return{ref:a,model:(0,y.chatGptModel)(a.model),searchTools:{search:(0,y.chatGptSearch)()}};case"anthropic":{let c=(0,d.createAnthropic)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch_20260209()}}}case"google":{let c=(0,j.createGoogleGenerativeAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.googleSearch({})}}}case"xai":{let c=(0,o.createXai)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"mistral":return P(a,(0,l.createMistral)({apiKey:b})(a.model));case"deepseek":return P(a,(0,h.createDeepSeek)({apiKey:b})(a.model));case"groq":return P(a,(0,k.createGroq)({apiKey:b})(a.model));case"cerebras":return P(a,(0,e.createCerebras)({apiKey:b})(a.model));case"togetherai":return P(a,(0,n.createTogetherAI)({apiKey:b})(a.model));case"fireworks":return P(a,(0,i.createFireworks)({apiKey:b})(a.model));case"deepinfra":return P(a,(0,g.createDeepInfra)({apiKey:b})(a.model));case"cohere":return P(a,(0,f.createCohere)({apiKey:b})(a.model));case"vercel-ai-gateway":{let c=(0,q.createGateway)({apiKey:b});return{ref:a,model:c(a.model),searchTools:null}}default:(0,w.publicError)(`Not supported provider: ${String(a.provider)}`)}}(a,r)}async function L(a,{quiet:b=!1}={}){let c=async a=>(0,z.defaultModelOf)({defaultTier:"chatgpt"===a.id&&await (0,y.readChatGptPlan)()==="free"?"small":a.defaultTier,suggestModels:await J(a.id,a.suggestModels)}),d=a?z.TEXT_MODEL_PROVIDER_LIST.find(b=>b.id===a):void 0,e=["chatgpt","openai","xai"].map(a=>({...z.TEXT_MODEL_PROVIDERS[a],id:a}));if(d){let a=await c(d);if(a)return{provider:d.id,model:a}}let f=(0,z.parseTextModel)(await (0,u.readConfig)(t.DEFAULT_MODEL_KEY)??void 0);if(f){let{label:a,apiKeyName:b,signIn:c}=z.TEXT_MODEL_PROVIDERS[f.provider];if(await (0,u.readConfig)(b))return f;(0,w.publicError)(c?`The default model is ${f.model} on ${a}, which is signed out — sign in again, or pick another in Settings › Models.`:`The default model is ${f.model}, and there is no ${a} key any more — add it in Settings › API keys, or pick another in Settings › Models.`)}for(let a of[...e,...z.TEXT_MODEL_PROVIDER_LIST]){if(!await (0,u.readConfig)(a.apiKeyName))continue;let d=await c(a);if(d)return b||v.logger.info(`no model set, falling back to ${a.id}/${d}`),{provider:a.id,model:d}}(0,w.publicError)("No model key is set — add one in Settings › API keys.")}async function M(a){let b=(0,z.parseMediaModel)(await (0,u.readConfig)(t.MEDIA_MODEL_KEYS[a]));if(!b||!(0,z.canMakeKind)(b.provider,a))return null;let c=await (0,u.readConfig)(z.MEDIA_MODEL_PROVIDERS[b.provider].apiKeyName);return c?{ref:b,apiKey:c}:null}a.s(["buildImageModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).image(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).image(a.model);case"xai":return(0,o.createXai)({apiKey:b}).image(a.model);case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).image(a.model);default:(0,w.publicError)(`Not supported image provider: ${String(a.provider)}`)}},"buildSpeechModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).speech(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).speech(a.model);case"xai":return(0,o.createXai)({apiKey:b}).speech();case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).speech(a.model);default:(0,w.publicError)(`Not supported speech provider: ${String(a.provider)}`)}},"buildTranscriptionModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).transcription(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).transcription(a.model);case"xai":return(0,o.createXai)({apiKey:b}).transcription();case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).transcription(a.model);default:(0,w.publicError)(`Not supported transcription provider: ${String(a.provider)}`)}},"buildVideoModel",0,function(a,b){switch(a.provider){case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).video(a.model);case"xai":return(0,o.createXai)({apiKey:b}).video(a.model);case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).video(a.model);default:(0,w.publicError)(`${a.provider} has no video model`)}},"compactBudget",0,F,"getTextModel",0,K,"isContextOverflow",0,B,"isProviderRefusal",0,function(a){return!B(a)&&C(a).some(a=>{let{statusCode:b}=a;return"number"==typeof b&&b>=400&&b<500&&!O.has(b)})},"modelErrorToString",0,function(a){if(!p.APICallError.isInstance(a))return(0,x.errorToString)(a);let b=a.statusCode?` (${a.statusCode})`:"",c=a.responseBody?.trim(),d=c&&!c.includes(a.message)?` ${(0,x.clip)(c,300)}`:"";return`${a.message}${b}${d}`},"resolveDefaultModel",0,L,"resolveMediaRef",0,M,"runEffort",0,H,"seesToolImages",0,function(a){let b="vercel-ai-gateway"===a.provider?z.GATEWAY_OWNERS[a.model.split("/")[0]]:a.provider;return void 0!==b&&["openai","chatgpt","anthropic","google","xai"].includes(b)}]),c()}catch(a){c(a)}},!1),735502,a=>a.a(async(b,c)=>{try{var d=a.i(12208),e=a.i(569572),f=a.i(884780),g=a.i(762008),h=a.i(641301),i=a.i(221214),j=a.i(446957),k=a.i(636616),l=a.i(344853),m=a.i(947950),n=a.i(986743),o=a.i(138100),p=a.i(684321),q=a.i(821415),r=a.i(706210),s=a.i(182248),t=a.i(644468),u=a.i(938934),v=b([i,l,m,n,o,t]);async function w(a,b,c,f){var k,v,w,z,A,B,C,D,E,F;let G,H,I,J,K,L,M,N=await (0,q.openWorkspace)(),O=a.trim(),[P,Q,R,S,T,U,V,W,X]=await Promise.all([(0,o.loadSkills)(N,O),(0,n.listNoteIndex)(),(0,t.listConnectedToolNames)(),(0,m.findPinnedTools)(O),(0,i.listJobBots)(),(0,h.listBotMemory)(O),(0,i.readBotMemoryOn)(),(0,q.readMachineTools)(N),(0,l.listBotWork)(O,c?.thread??null)]),Y=T.filter(a=>a.name!==O),Z=T.find(a=>a.name===O)??await (0,i.findJobBot)(O),$=[(k=O,v=Z,w=c,H=(G=w?.owner??k)===k?"**You** coordinate this thread: its result goes from you to Thursday.":`**${G}** coordinates this thread and brings its result to Thursday.`,I=w?`
|
|
1
|
+
module.exports=[652619,a=>a.a(async(b,c)=>{try{var d=a.i(666680),e=a.i(347299),f=a.i(345364),g=a.i(47919),h=a.i(868468),i=a.i(53112),j=a.i(569572),k=a.i(725466),l=a.i(176668),m=a.i(523095),n=a.i(293480),o=a.i(8412),p=a.i(182248),q=a.i(689656),r=b([k]);[k]=r.then?(await r)():r;let D="app_EMoamEEZ73f0CkXaXp7hrann",E="http://localhost:1455/auth/callback",F=["127.0.0.1","::1"],G="thursday",{apiKeyName:H,label:I}=q.TEXT_MODEL_PROVIDERS.chatgpt,J=`${I} is not signed in — sign in from Settings › API keys.`,K=i.z.object({access:i.z.string().min(1),refresh:i.z.string().min(1),expires:i.z.number(),accountId:i.z.string().min(1),plan:i.z.string().nullable()}),L=globalThis,M=L.__chatgptRenewal??=(0,o.createKeyedLock)();async function s(){t();let a=(0,d.randomBytes)(32).toString("base64url"),b=(0,d.randomBytes)(16).toString("hex"),c=[],f=(d,e)=>{u(d.url??"/",{state:b,verifier:a}).then(a=>{e.writeHead(a.status,{"content-type":"text/html; charset=utf-8"}),e.end((0,m.oauthPage)(a.title,a.detail,{autoClose:200===a.status}),()=>{a.last&&L.__chatgptListeners===c&&t()})})};for(let a of F){let b=(0,e.createServer)(f),d=await new Promise(c=>{b.once("error",c),b.listen(1455,a,()=>c(null))});if(!d){c.push(b);continue}if("EADDRNOTAVAIL"!==d.code&&"EAFNOSUPPORT"!==d.code){for(let a of c)a.close();(0,n.publicError)("EADDRINUSE"===d.code?"Port 1455 is in use by another app — often a ChatGPT or Codex sign-in still waiting. Finish or close it, then try again.":`Could not wait for the sign-in: ${(0,p.errorToString)(d)}`)}}L.__chatgptListeners=c,setTimeout(()=>{L.__chatgptListeners===c&&t()},j.CHATGPT_SIGN_IN.waitMs).unref();let g=new URL("https://auth.openai.com/oauth/authorize");return g.search=new URLSearchParams({response_type:"code",client_id:D,redirect_uri:E,scope:"openid profile email offline_access",code_challenge:(0,d.createHash)("sha256").update(a).digest("base64url"),code_challenge_method:"S256",state:b,id_token_add_organizations:"true",codex_cli_simplified_flow:"true",originator:G}).toString(),g.toString()}function t(){let a=L.__chatgptListeners;for(let b of(L.__chatgptListeners=null,a??[]))b.close(),b.closeIdleConnections()}async function u(a,b){let c=new URL(a,E);if("/auth/callback"!==c.pathname)return{status:404,title:"Not found",detail:"",last:!1};let d=c.searchParams.get("error");if(d){let a=c.searchParams.get("error_description");return{status:400,title:"Sign-in failed",detail:a?`${d}: ${a}`:d,last:!0}}let e=c.searchParams.get("code");if(!e||c.searchParams.get("state")!==b.state)return{status:400,title:"Sign-in failed",detail:"This is not the sign-in that was started. Start again from Settings › API keys.",last:!1};try{let a=await v({grant_type:"authorization_code",code:e,code_verifier:b.verifier,redirect_uri:E});return await (0,k.writeConfig)(H,JSON.stringify(a)),{status:200,title:"Signed in to ChatGPT",detail:"Bots can run on your plan now. This window closes itself.",last:!0}}catch(a){return l.logger.warn({cause:a},"chatgpt sign-in failed"),{status:502,title:"Sign-in failed",detail:(0,p.errorToString)(a),last:!0}}}async function v(a){let b=await fetch("https://auth.openai.com/oauth/token",{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:D,...a})}).catch(a=>{l.logger.warn({cause:a},"chatgpt token endpoint unreachable"),(0,n.publicError)("Could not reach ChatGPT's sign-in")}),c=await b.json().catch(()=>null),d=c?.access_token;if(!b.ok||!d){let a=c?.error,d="string"==typeof a?[a,c?.error_description].filter(Boolean).join(": "):a?.message??a?.code??"";(0,n.publicError)(`ChatGPT's sign-in answered ${b.status}${d?`: ${d}`:""}`)}let e=function(a){try{let b=JSON.parse(Buffer.from(a.split(".")[1]??"","base64url").toString("utf8")),c=b["https://api.openai.com/auth"]??{};return{accountId:"string"==typeof c.chatgpt_account_id?c.chatgpt_account_id:null,plan:"string"==typeof c.chatgpt_plan_type?c.chatgpt_plan_type:null,expires:"number"==typeof b.exp?1e3*b.exp:null}}catch{return{accountId:null,plan:null,expires:null}}}(d),f=c?.refresh_token??a.refresh_token;e.accountId&&f||(0,n.publicError)("ChatGPT's sign-in came back without an account");let g=c?.expires_in;return{access:d,refresh:f,expires:"number"==typeof g?Date.now()+1e3*g:e.expires??Date.now(),accountId:e.accountId,plan:e.plan}}async function w(){let a=await (0,k.readConfig)(H);if(!a)return null;try{return K.parse(JSON.parse(a))}catch{return null}}let N=a=>a.expires-j.CHATGPT_SIGN_IN.renewBeforeMs<=Date.now();async function x(){let a=await w();return(a||(0,n.publicError)(J),N(a))?M(H,async()=>{let a=await w();if(a||(0,n.publicError)(J),!N(a))return a;try{let b=await v({grant_type:"refresh_token",refresh_token:a.refresh});return await (0,k.writeConfig)(H,JSON.stringify(b)),b}catch(a){(0,n.publicError)(`Could not renew the ${I} sign-in (${(0,p.errorToString)(a)}). If it keeps failing, sign in again from Settings › API keys.`)}}):a}async function y(){return(await w())?.plan??null}async function z(a,b){let c=await x(),d=new Headers(b?.headers);if(d.set("authorization",`Bearer ${c.access}`),d.set("chatgpt-account-id",c.accountId),d.set("originator",G),b?.method!=="POST"||"string"!=typeof b.body||!String(a).endsWith("/responses"))return fetch(a,{...b,headers:d});let e=JSON.parse(b.body),f=!0===e.stream;e.prompt_cache_key&&d.set("session-id",e.prompt_cache_key);let g=[];e.input=(e.input??[]).filter(a=>"system"!==a.role&&"developer"!==a.role||(g.push("string"==typeof a.content?a.content:(a.content??[]).map(a=>a.text??"").join("\n")),!1)),e.instructions=[e.instructions,...g].filter(Boolean).join("\n\n")||"You are a helpful assistant.",e.store=!1,e.stream=!0,e.max_output_tokens=void 0,d.set("accept","text/event-stream");let h=await fetch(a,{...b,headers:d,body:JSON.stringify(e)});return 429===h.status?B(h):h.ok?f?h:C(h):A(h)}async function A(a){let b=await a.clone().json().catch(()=>null);if("string"!=typeof b?.detail)return a;let c=a.headers.get("retry-after");return Response.json({error:{message:b.detail}},{status:a.status,headers:c?{"retry-after":c}:{}})}async function B(a){let b=await a.text(),c={};try{c=JSON.parse(b).error??{}}catch{}if(!/usage_limit_reached|usage_not_included/.test(`${c.code} ${c.type}`)){let c=a.headers.get("retry-after");return new Response(b,{status:429,headers:{"content-type":"application/json",...c?{"retry-after":c}:{}}})}let d=c.resets_at?1e3*c.resets_at:c.resets_in_seconds?Date.now()+1e3*c.resets_in_seconds:null,e=c.plan_type?` on the ${c.plan_type} plan`:"",f=d?` It resets in ${(0,h.formatDistanceToNowStrict)(d)}.`:"";return Response.json({error:{message:`${I} usage limit reached${e}.${f}`,code:c.code??c.type}},{status:402})}async function C(a){let b=[],c=null,d=null;for(let e of(await a.text()).replaceAll("\r\n","\n").split("\n\n")){let a,f=e.split("\n").filter(a=>a.startsWith("data:")).map(a=>a.slice(5).trimStart()).join("\n");if(f&&"[DONE]"!==f){try{a=JSON.parse(f)}catch{continue}"response.output_item.done"===a.type?b.push(a.item):"response.completed"===a.type||"response.incomplete"===a.type?c=a.response??{}:"response.failed"===a.type?d=a.response?.error??{message:"The response failed"}:"error"===a.type&&(d={code:a.code,message:a.message})}}return d||!c?Response.json({error:{message:d?.message??"The stream ended before the response finished",code:d?.code}},{status:d?.code==="context_length_exceeded"?400:500}):Response.json({...c,output:c.output?.length?c.output:b})}a.s(["chatGptModel",0,function(a){let b=(0,f.createOpenAI)({baseURL:"https://chatgpt.com/backend-api/codex",apiKey:"signed-in",headers:{"OpenAI-Beta":"responses=experimental"},fetch:z}),c=(0,d.randomUUID)();return(0,g.wrapLanguageModel)({model:b.responses(a),middleware:{transformParams:async({params:a})=>({...a,providerOptions:{...a.providerOptions,openai:{promptCacheKey:c,...a.providerOptions?.openai,store:!1,includeWebSearchSources:!1}}})}})},"chatGptSearch",0,()=>(0,f.createOpenAI)({apiKey:"signed-in"}).tools.webSearch(),"readChatGptPlan",0,y,"startChatGptSignIn",0,s]),c()}catch(a){c(a)}},!1),884780,a=>{"use strict";a.i(902157),a.i(912714);var b=a.i(750227),c=a.i(569572);(0,b.join)(c.APP_DIR,"guide");let d=".guide";a.s(["botGuideLine",0,()=>`How ${c.APP_NAME} itself works for the user — its screens and settings — is written under \`${d}/\` here, \`index.md\` first; read it only when the job is about the app.`,"guideLine",0,()=>`How ${c.APP_NAME} works for the person using it — its screens, its settings, what it connects to, what to do when something stops — is written under \`${d}/\` here, \`index.md\` first. Read it whenever an answer depends on how the app works: what can be asked for, where something is changed, a wish that needs a setting switched on, something that stopped or was refused. Answer from it rather than from what you assume.`])},738131,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(868468),f=a.i(569572),g=a.i(875931),h=a.i(938934),i=a.i(978876),j=a.i(375827),k=a.i(127507),l=a.i(467650),m=a.i(138902),n=a.i(345846),o=a.i(617594),p=a.i(622547),q=a.i(128232),r=a.i(382442),s=a.i(451017),t=a.i(762008),u=a.i(547613),v=a.i(446957),w=a.i(138100),x=a.i(821415),y=a.i(706210),z=a.i(176668),A=a.i(293480),B=a.i(987674),C=a.i(182248),D=b([g,i,m,n,o,p,q,s,w]);async function E(b){let{listThreadOverview:c}=await a.A(343064),d=await c();if(!d.length)return"No thread has been started yet.";let e=d.map(a=>`"${a.label}" (${a.bot}, ${a.status})`).join(", ");return`There is no thread called "${b}". The latest are: ${e}. Call again with one of those labels.`}async function F(a,b){let c=[];for(let[a,e]of Object.entries(b)){let b=await (0,d.asSchema)(e.inputSchema).jsonSchema,f="string"==typeof e.description?e.description:"";c.push({name:a,tokens:(0,B.estimateTokens)(f)+(0,B.estimateTokens)(JSON.stringify(b))})}c.sort((a,b)=>b.tokens-a.tokens);let e=c.reduce((a,b)=>a+b.tokens,0);z.logger.debug(`${a} tools ${e} tokens over ${c.length} — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`)}async function G(a){let b=await H(a);return f.IS_DEV&&await F(a.target,b),b}async function H(b){if("memory-edit"===b.target)return(0,n.createMemoryTools)("user",null,{countReads:!1});let c=(0,n.createMemoryTools)("call","thursday"===b.target?b.callId??null:null),z=await (0,x.openWorkspace)();if("thursday"===b.target){var B;let k,m,n=b.readSkills?(0,s.createSkillTools)({sandbox:z,skills:await (0,w.loadSkills)(z)}):{},q=!!(b.written&&b.model&&(0,g.seesToolImages)(b.model));return{...c,...n,...(0,u.createWorkspaceTools)(z,{write:!1,timeoutMs:f.CALL_EXEC_TIMEOUT_MS}),...!1===b.webSearch?{}:await (0,p.createCallSearchTool)(z),...Object.fromEntries(Object.entries((B=b.callId,k=async b=>{let{resolveThread:c}=await a.A(343064);return(b.trim()?await c(b.trim()):null)??await E(b)},m=async(b,c,d)=>{let e=await a.A(763543);try{return await e.answerThread(b,c,"thursday",d)}catch(a){if((0,A.isPublicError)(a))return a.message;throw a}},{[t.TOOL_NAMES.thread_start]:(0,d.tool)({description:i.threadStartSpec.description,inputSchema:i.threadStartSpec.parameters,execute:async({bot:b,request:c,label:d})=>{let{findJobBot:e,listJobBots:f}=await a.A(276307),g=await e(b);if(!g||g.disabled){let a=(await f()).map(a=>a.name);return`There is no bot called "${b}". The bots are: ${a.join(", ")}. Nothing was started — call again with one of those.`}let{startThread:h}=await a.A(763543);return{threadId:await h({bot:g.name,request:c,label:d,callId:B,from:"thursday"}),bot:g.name,label:d,note:`${g.name} has "${d}". Its updates reach the conversation on their own. Anything further about this work — a correction, the next step once it finishes — is \`${t.TOOL_NAMES.thread_tell}\` with "${d}"; a question it asks is answered with \`${t.TOOL_NAMES.thread_answer}\`.`}}}),[t.TOOL_NAMES.thread_tell]:(0,d.tool)({description:i.threadTellSpec.description,inputSchema:i.threadTellSpec.parameters,execute:async({thread:a,words:b})=>{let c=await k(a);if("string"==typeof c)return c;if(!b.trim())return"Say what to pass on.";let d=await m(c.id,b.trim());return"string"==typeof d?d:d?.answered?{label:c.label,answered:d.answered,note:`${d.answered.bot} was waiting on a question, and took this as its answer.`}:{label:c.label,bot:d?.to??c.bot,status:"running",note:"running"===c.status?"The bot reads it before its next step.":"The bot picks the thread back up from there."}}}),[t.TOOL_NAMES.thread_answer]:(0,d.tool)({description:i.threadAnswerSpec.description,inputSchema:i.threadAnswerSpec.parameters,execute:async({thread:b,bot:c,answer:d})=>{let e=await k(b);if("string"==typeof e)return e;if(!d.trim())return"Say what the answer is.";let{findThreadView:f}=await a.A(343064),g=(await f(e.id))?.room.questions??[],h=g.find(a=>a.bot.toLowerCase()===c.trim().toLowerCase());if(!h)return g.length?`${c} is not asking anything in "${e.label}". Waiting there: ${g.map(a=>a.bot).join(", ")}. Call again with that bot.`:`No question is waiting in "${e.label}". To say something else to it, use \`${t.TOOL_NAMES.thread_tell}\`.`;let i=await m(e.id,d.trim(),h.bot);return"string"==typeof i?i:{label:e.label,answered:i?.answered??{bot:h.bot,question:h.text},note:`${h.bot} has the answer to its question and goes on from it.`}}}),[t.TOOL_NAMES.thread_status]:(0,d.tool)({description:i.threadStatusSpec.description,inputSchema:i.threadStatusSpec.parameters,execute:async({thread:b})=>{let{listThreadOverview:c,findThreadView:d}=await a.A(343064),g={now:(0,h.clockNow)()},i=a=>(0,e.formatDistanceToNowStrict)((0,y.toDate)(a),{addSuffix:!0});if(!(!b.trim()||"all"===b.trim().toLowerCase())){let a=await k(b);if("string"==typeof a)return a;let c=(await d(a.id))?.room;return{...g,label:a.label,id:a.id,bot:a.bot,participants:c?.participants??[],questions:c?.questions??[],status:a.status,since:i(a.updatedAt),outcome:a.outcome,..."waiting"===a.status&&a.pending?.options.length?{options:a.pending.options}:{}}}let j=await c();return j.length?{...g,threads:j.map(a=>({id:a.id,label:a.label,bot:a.bot,status:a.status,participants:a.room.participants,questions:a.room.questions.map(a=>({...a,text:(0,C.clip)(a.text,f.PROMPT_LINE.threadStatus)})),since:i(a.updatedAt),...a.ask?{asking:a.ask.question,options:a.ask.options}:{},..."running"===a.status?{now:(0,v.threadActivity)(a.lines)}:{},...a.outcome&&"waiting"!==a.status?{outcome:(0,C.clip)(a.outcome,f.PROMPT_LINE.threadStatus)}:{}}))}:"No thread has been started yet."}}),[t.TOOL_NAMES.thread_cancel]:(0,d.tool)({description:i.threadCancelSpec.description,inputSchema:i.threadCancelSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{cancelThread:d}=await a.A(763543);return await d(c.id),{label:c.label,status:"cancelled"}}}),[t.TOOL_NAMES.thread_show]:(0,d.tool)({description:i.threadShowSpec.description,inputSchema:i.threadShowSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{appEvents:d}=await a.A(133300),{filesOnDisk:e}=await a.A(122690),{leadFirst:f,pathsIn:g,viewKindOf:h}=await a.A(394298),i=(await e(g(c.outcome??""),null)).filter(a=>"none"!==h(a));if(!i.length)return d.emit({type:"showThread",threadId:c.id}),{label:c.label,showing:"the thread"};let j=f(i);d.emit({type:"showFile",paths:j});let{markSeen:l}=await a.A(343064);return await l([c.id]),{label:c.label,showing:j[0]}}}),[t.TOOL_NAMES.thread_seen]:(0,d.tool)({description:i.threadSeenSpec.description,inputSchema:i.threadSeenSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{markSeen:d}=await a.A(343064);return await d([c.id]),{label:c.label,seen:!0}}})})).filter(([a])=>!(b.phone&&a===t.TOOL_NAMES.thread_show))),...(0,o.createRoutineTools)(),...q?(0,l.createLookTool)():{},...b.written?{}:(0,j.callTools)()}}let D=await (0,w.loadSkills)(z,b.bot),F={...(0,x.jobShellEnv)(b.session),...(0,x.botShellEnv)(b.bot,(await (await a.A(276307)).findJobBot(b.bot))?.icon)},G=!!(b.model&&(0,g.seesToolImages)(b.model.ref));return{[t.TOOL_NAMES.memory_recall]:(0,n.createMemoryTools)("call",null,{tidies:!1})[t.TOOL_NAMES.memory_recall],...await (0,p.createSearchTool)(b.model,z),...(0,u.createWorkspaceTools)(z,{write:!0,env:F,guide:!0,bot:b.bot}),...await (0,m.createMcpTools)(b.bot,z),...(0,s.createSkillTools)({sandbox:z,skills:D,bot:b.bot}),...await (0,q.createSelfTools)(b.bot),...(0,k.createDeckTools)(z,b.bot,F,G),...G?(0,l.createLookTool)():{},...(0,r.createSignInTools)(z,b.bot,(0,x.jobShellEnv)(b.session)),...await (0,i.createThreadRecallTool)(b.bot,b.thread??null)}}[g,i,m,n,o,p,q,s,w]=D.then?(await D)():D,a.s(["loadTools",0,G]),c()}catch(a){c(a)}},!1),822164,a=>a.a(async(b,c)=>{try{a.i(569572);var d=a.i(725466),e=a.i(176668),f=a.i(293480),g=a.i(689656),h=b([d]);[d]=h.then?(await h)():h;let k={"x-ai":"spacexai","z-ai":"zai",mistralai:"mistral","meta-llama":"meta",qwen:"alibaba","bytedance-seed":"bytedance"},l=a=>{let b=a.slice(0,a.indexOf("/")).replace(/^~/,"");return k[b]??b};function i(a){if(null==a||""===a)return null;let b=Number(a);return!Number.isFinite(b)||b<0?null:Math.round(1e6*b*1e4)/1e4}async function j(){let a=await fetch("https://openrouter.ai/api/v1/models",{headers:{accept:"application/json"}}).catch(a=>{e.logger.warn({cause:a},"openrouter catalog unreachable"),(0,f.publicError)("Could not reach OpenRouter")});return a.ok||(0,f.publicError)(`OpenRouter answered ${a.status}`),((await a.json()).data??[]).filter(a=>!!a.id).map(a=>{let b,c,d,e;return{id:a.id,label:a.name||a.id,owner:l(a.id),type:(a.architecture?.output_modalities??[]).includes("text")?g.CATALOG_TEXT:null,tags:(a.supported_parameters??[]).includes("tools")?[g.CATALOG_TOOL_USE]:[],price:(b=i(a.pricing?.prompt),c=i(a.pricing?.completion),0===b&&0===c?{in:0,out:0,note:null,free:!0}:{in:b,out:c,note:null===b&&null===c?"per model it picks":null,free:!1}),retiring:!!a.expiration_date,contextWindow:"number"==typeof a.context_length&&a.context_length>0?a.context_length:null,efforts:(d=a.reasoning?.supported_efforts??[],(e=g.EFFORTS.filter(a=>d.includes(a))).length?e:null)}})}a.s(["fetchOpenRouterCatalog",0,j,"vendorOf",0,l]),c()}catch(a){c(a)}},!1),875931,a=>a.a(async(b,c)=>{try{var d=a.i(938537),e=a.i(674861),f=a.i(606016),g=a.i(388319),h=a.i(538177),i=a.i(767071),j=a.i(140358),k=a.i(873739),l=a.i(899042),m=a.i(345364),n=a.i(434451),o=a.i(655819),p=a.i(272380),q=a.i(652685),r=a.i(156956),s=a.i(47919),t=a.i(569572),u=a.i(688034),v=a.i(725466),w=a.i(176668),x=a.i(293480),y=a.i(182248),z=a.i(652619),A=a.i(689656),B=a.i(822164),C=b([v,z,B]);[v,z,B]=C.then?(await C)():C;let Q=/context[ _-]?(length|window)|maximum context|prompt is too long|too many (input )?tokens|input token count|exceeds? the (maximum|model'?s?) (context|input|prompt|number of tokens)|maximum prompt length|request (entity )?too large/i;function D(a){return E(a).some(a=>{let{statusCode:b,message:c,error:d}=a;if(void 0!==b&&400!==b&&413!==b)return!1;let e=q.APICallError.isInstance(a)?a.responseBody:null;return[c,d,e].some(a=>"string"==typeof a&&Q.test(a))})}let R=new Set([408,409,429]);function E(a){let b=[],c=[a];for(;c.length&&b.length<12;){let a=c.shift();!("object"!=typeof a||null===a||b.includes(a))&&(b.push(a),s.RetryError.isInstance(a)&&c.push(...a.errors),"cause"in a&&c.push(a.cause))}return b}let S=(a,b)=>({ref:a,model:b,searchTools:null}),T={};function F(a){if(null==a||""===a)return null;let b=Number(a);return Number.isFinite(b)?Math.round(1e6*b*1e4)/1e4:null}async function G(a){let b=T[a];if(b&&Date.now()-b.at<t.CATALOG_MS)return b.models;let c=("openrouter"===a?await (0,B.fetchOpenRouterCatalog)():await H()).sort((a,b)=>a.id.localeCompare(b.id));return T[a]={at:Date.now(),models:c},c}async function H(){let a=await fetch("https://ai-gateway.vercel.sh/v1/models",{headers:{accept:"application/json"}}).catch(a=>{w.logger.warn({cause:a},"gateway catalog unreachable"),(0,x.publicError)("Could not reach the gateway")});return a.ok||(0,x.publicError)(`The gateway answered ${a.status}`),((await a.json()).data??[]).filter(a=>!!a.id).map(a=>{let b,c;return{id:a.id,label:a.name||a.id,owner:a.owned_by||a.id.slice(0,a.id.indexOf("/")),type:a.type??null,tags:a.tags??[],price:function(a){let b=a.pricing??{},c=F(b.input),d=F(b.output);if((a.tags??[]).includes("free")||0===c)return{in:0,out:0,note:null,free:!0};let e=b.transcription_duration_cost_per_second??b.realtime_session_duration_cost_per_second;if(e)return{in:null,out:null,note:`$${e}/s`,free:!1};if(b.speech_input_character_cost)return{in:null,out:null,note:"per character",free:!1};let f=Array.isArray(b.video_duration_pricing)?b.video_duration_pricing[0]:null;if(f?.cost_per_second)return{in:null,out:null,note:`$${f.cost_per_second}/s ${f.resolution??""}`.trimEnd(),free:!1};let g=b.image?`$${b.image}/image`:b.image_dimension_quality_pricing?"per image, by size":null;return null===c&&null===d?{in:null,out:null,note:g,free:!1}:{in:c,out:d,note:b.input_tiers?"tiered":b.varies_by_provider?"varies":g&&"+ per image",free:!1}}(a),retiring:!!a.deprecated_at,contextWindow:"number"==typeof a.context_window&&a.context_window>0?a.context_window:null,efforts:(b=(a.reasoning_options??[]).find(a=>a?.type==="effort"),(c=A.EFFORTS.filter(a=>b?.values?.includes(a))).length?c:null)}})}async function I(a,b){if(b&&b>0)return b;let c=await J(a);return(0,A.compactAtFor)((0,A.contextWindowOf)(a.provider,a.model,c))}async function J(a){return(0,A.isCatalogProvider)(a.provider)?await G(a.provider).catch(()=>[]):[]}async function K(a,b){let c=b??A.effortSchema.safeParse(await (0,v.readConfig)(u.DEFAULT_EFFORT_KEY)).data;if(!c)return;let d=await J(a);return(0,A.effortsOf)(a.provider,a.model,d)?.includes(c)?c:void 0}async function L(a){return await G(a).then(a=>new Set(a.map(a=>a.id))).catch(()=>null)}async function M(a,b){if(!(0,A.isCatalogProvider)(a))return b;let c=await L(a);if(!c)return b;let d=b.filter(a=>c.has(a.id));return d.length>0?d:b}async function N(a){let{label:b,apiKeyName:c,signIn:q}=A.TEXT_MODEL_PROVIDERS[a.provider],t=await (0,v.readConfig)(c);return t||(0,x.publicError)(q?`${b} is not signed in — sign in from Settings › API keys.`:`No ${b} key — add one in Settings › API keys.`),function(a,b){switch(a.provider){case"openai":{let c=(0,m.createOpenAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"chatgpt":return{ref:a,model:(0,z.chatGptModel)(a.model),searchTools:{search:(0,z.chatGptSearch)()}};case"anthropic":{let c=(0,d.createAnthropic)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch_20260209()}}}case"google":{let c=(0,j.createGoogleGenerativeAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.googleSearch({})}}}case"xai":{let c=(0,o.createXai)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"mistral":return S(a,(0,l.createMistral)({apiKey:b})(a.model));case"deepseek":return S(a,(0,h.createDeepSeek)({apiKey:b})(a.model));case"groq":return S(a,(0,k.createGroq)({apiKey:b})(a.model));case"cerebras":return S(a,(0,e.createCerebras)({apiKey:b})(a.model));case"togetherai":return S(a,(0,n.createTogetherAI)({apiKey:b})(a.model));case"fireworks":return S(a,(0,i.createFireworks)({apiKey:b})(a.model));case"deepinfra":return S(a,(0,g.createDeepInfra)({apiKey:b})(a.model));case"cohere":return S(a,(0,f.createCohere)({apiKey:b})(a.model));case"vercel-ai-gateway":{let c=(0,r.createGateway)({apiKey:b});return{ref:a,model:c(a.model),searchTools:null}}case"openrouter":{var c;let d=(0,p.createOpenRouter)({apiKey:b});return{ref:a,model:(c=d(a.model),(0,s.wrapLanguageModel)({model:c,middleware:{specificationVersion:"v4",transformParams:async({params:a})=>a.reasoning&&"provider-default"!==a.reasoning?{...a,providerOptions:{...a.providerOptions,openrouter:{...a.providerOptions?.openrouter,reasoning:{effort:a.reasoning}}}}:a}})),searchTools:{search:d.tools.webSearch({})}}}default:(0,x.publicError)(`Not supported provider: ${String(a.provider)}`)}}(a,t)}async function O(a,{quiet:b=!1}={}){let c=async a=>(0,A.defaultModelOf)({defaultTier:"chatgpt"===a.id&&await (0,z.readChatGptPlan)()==="free"?"small":a.defaultTier,suggestModels:await M(a.id,a.suggestModels)}),d=a?A.TEXT_MODEL_PROVIDER_LIST.find(b=>b.id===a):void 0,e=["chatgpt","openai","xai"].map(a=>({...A.TEXT_MODEL_PROVIDERS[a],id:a}));if(d){let a=await c(d);if(a)return{provider:d.id,model:a}}let f=(0,A.parseTextModel)(await (0,v.readConfig)(u.DEFAULT_MODEL_KEY)??void 0);if(f){let{label:a,apiKeyName:b,signIn:c}=A.TEXT_MODEL_PROVIDERS[f.provider];if(await (0,v.readConfig)(b))return f;(0,x.publicError)(c?`The default model is ${f.model} on ${a}, which is signed out — sign in again, or pick another in Settings › Models.`:`The default model is ${f.model}, and there is no ${a} key any more — add it in Settings › API keys, or pick another in Settings › Models.`)}for(let a of[...e,...A.TEXT_MODEL_PROVIDER_LIST]){if(!await (0,v.readConfig)(a.apiKeyName))continue;let d=await c(a);if(d)return b||w.logger.info(`no model set, falling back to ${a.id}/${d}`),{provider:a.id,model:d}}(0,x.publicError)("No model key is set — add one in Settings › API keys.")}async function P(a){let b=(0,A.parseMediaModel)(await (0,v.readConfig)(u.MEDIA_MODEL_KEYS[a]));if(!b||!(0,A.canMakeKind)(b.provider,a))return null;let c=await (0,v.readConfig)(A.MEDIA_MODEL_PROVIDERS[b.provider].apiKeyName);return c?{ref:b,apiKey:c}:null}a.s(["buildImageModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).image(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).image(a.model);case"xai":return(0,o.createXai)({apiKey:b}).image(a.model);case"vercel-ai-gateway":return(0,r.createGateway)({apiKey:b}).image(a.model);default:(0,x.publicError)(`Not supported image provider: ${String(a.provider)}`)}},"buildSpeechModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).speech(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).speech(a.model);case"xai":return(0,o.createXai)({apiKey:b}).speech();case"vercel-ai-gateway":return(0,r.createGateway)({apiKey:b}).speech(a.model);default:(0,x.publicError)(`Not supported speech provider: ${String(a.provider)}`)}},"buildTranscriptionModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).transcription(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).transcription(a.model);case"xai":return(0,o.createXai)({apiKey:b}).transcription();case"vercel-ai-gateway":return(0,r.createGateway)({apiKey:b}).transcription(a.model);default:(0,x.publicError)(`Not supported transcription provider: ${String(a.provider)}`)}},"buildVideoModel",0,function(a,b){switch(a.provider){case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).video(a.model);case"xai":return(0,o.createXai)({apiKey:b}).video(a.model);case"vercel-ai-gateway":return(0,r.createGateway)({apiKey:b}).video(a.model);default:(0,x.publicError)(`${a.provider} has no video model`)}},"compactBudget",0,I,"getTextModel",0,N,"isContextOverflow",0,D,"isProviderRefusal",0,function(a){return!D(a)&&E(a).some(a=>{let{statusCode:b}=a;return"number"==typeof b&&b>=400&&b<500&&!R.has(b)})},"modelErrorToString",0,function(a){if(!q.APICallError.isInstance(a))return(0,y.errorToString)(a);let b=a.statusCode?`(${a.statusCode})`:"",c=a.responseBody?.trim(),d=c&&!(a.message&&c.includes(a.message))?(0,y.clip)(c,300):"";return[a.message,b,d].filter(Boolean).join(" ")},"promptCacheOptions",0,function(a,b){switch(a.provider){case"openai":case"chatgpt":return b?{openai:{promptCacheKey:b}}:{};case"anthropic":return{anthropic:{cacheControl:{type:"ephemeral"}}};case"vercel-ai-gateway":return{gateway:{caching:"auto"}};case"openrouter":return"anthropic"===(0,B.vendorOf)(a.model)?{openrouter:{cacheControl:{type:"ephemeral"}}}:{};default:return{}}},"resolveDefaultModel",0,O,"resolveMediaRef",0,P,"runEffort",0,K,"seesToolImages",0,function(a){let b="vercel-ai-gateway"===a.provider?A.VENDOR_PROVIDERS[a.model.split("/")[0]]:"openrouter"===a.provider?A.VENDOR_PROVIDERS[(0,B.vendorOf)(a.model)]:a.provider;return void 0!==b&&["openai","chatgpt","anthropic","google","xai"].includes(b)}]),c()}catch(a){c(a)}},!1),735502,a=>a.a(async(b,c)=>{try{var d=a.i(12208),e=a.i(569572),f=a.i(884780),g=a.i(762008),h=a.i(641301),i=a.i(221214),j=a.i(446957),k=a.i(636616),l=a.i(344853),m=a.i(947950),n=a.i(986743),o=a.i(138100),p=a.i(684321),q=a.i(821415),r=a.i(706210),s=a.i(182248),t=a.i(644468),u=a.i(938934),v=b([i,l,m,n,o,t]);async function w(a,b,c,f){var k,v,w,z,A,B,C,D,E,F;let G,H,I,J,K,L,M,N=await (0,q.openWorkspace)(),O=a.trim(),[P,Q,R,S,T,U,V,W,X]=await Promise.all([(0,o.loadSkills)(N,O),(0,n.listNoteIndex)(),(0,t.listConnectedToolNames)(),(0,m.findPinnedTools)(O),(0,i.listJobBots)(),(0,h.listBotMemory)(O),(0,i.readBotMemoryOn)(),(0,q.readMachineTools)(N),(0,l.listBotWork)(O,c?.thread??null)]),Y=T.filter(a=>a.name!==O),Z=T.find(a=>a.name===O)??await (0,i.findJobBot)(O),$=[(k=O,v=Z,w=c,H=(G=w?.owner??k)===k?"**You** coordinate this thread: its result goes from you to Thursday.":`**${G}** coordinates this thread and brings its result to Thursday.`,I=w?`
|
|
2
2
|
|
|
3
3
|
Current conversation: ${w.caller} → ${k}. Your final text goes back to ${w.caller}.`:"",J=v?`
|
|
4
|
-
Others know you as: ${(0,j.rosterLine)(v)}`:"",`You are ${k}, one of the bots in this thread. ${(0,u.
|
|
4
|
+
Others know you as: ${(0,j.rosterLine)(v)}`:"",`You are ${k}, one of the bots in this thread. ${(0,u.todayLine)()}${J}
|
|
5
5
|
|
|
6
6
|
- **The user** — the one person all of this is for. They talk with Thursday by voice and follow this thread on their screen.
|
|
7
7
|
- **Thursday** — their personal assistant. She talks with them, hands bots the work that takes time, and tells them what comes back.
|
|
@@ -76,17 +76,19 @@ ${(0,f.botGuideLine)()}`};a.s(["buildThreadOpening",0,function(a){if(a.routine){
|
|
|
76
76
|
|
|
77
77
|
${a.request.trim()}`}]}let b="user"===a.from?"The user":"Thursday";return[{type:"text",text:`You are ${a.bot}. ${b} hands you this thread${"user"===a.from?" on screen":" during a call"}.`},{type:"text",text:`## ${b} → ${a.bot}: the job
|
|
78
78
|
|
|
79
|
-
${a.request.trim()}`}]},"loadBotPrompt",0,w]),c()}catch(a){c(a)}},!1),938934,a=>{"use strict";var b=a.i(12208),c=a.i(868468),d=a.i(569572),e=a.i(762008),f=a.i(951941),g=a.i(626550),h=a.i(706210),i=a.i(176668),j=a.i(987674),k=a.i(182248);let l=(a=new Date)=>`${(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm")} ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,m=(a
|
|
79
|
+
${a.request.trim()}`}]},"loadBotPrompt",0,w]),c()}catch(a){c(a)}},!1),938934,a=>{"use strict";var b=a.i(12208),c=a.i(868468),d=a.i(569572),e=a.i(762008),f=a.i(951941),g=a.i(626550),h=a.i(706210),i=a.i(176668),j=a.i(987674),k=a.i(182248);let l=(a=new Date)=>`${(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm")} ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,m=a=>(0,b.format)(a,"yyyy-MM-dd (EEE) a"),n=a=>`${(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm")} (${(0,c.formatDistanceToNowStrict)(a,{addSuffix:!0})})`,o={[e.STUDIO_TOOLS.generate_image]:"images",[e.STUDIO_TOOLS.generate_speech]:"speech",[e.STUDIO_TOOLS.transcribe]:"transcription",[e.STUDIO_TOOLS.generate_video]:"video"};a.s(["botWorkHead",0,function(a,c){let d=m(a.updatedAt),e="running"===a.status?`running, last moved ${d}`:a.asking?`waiting on the user's answer since ${d}`:"waiting"===a.status?`stopped ${d}, not finished`:`${"done"===a.status?"ended":"stopped by the user"} ${(0,b.format)(a.updatedAt,"yyyy-MM-dd")}`;return`"${a.label}" — ${a.owner===c?"yours":`${a.owner}'s`} — ${e}`},"clockNow",0,l,"logPromptSize",0,function(a,b){let c=(0,j.sectionTokens)(b),e=c.reduce((a,b)=>a+b.tokens,0);i.logger.debug(`${a} prompt ${e} tokens — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`);let f=c[0];e>d.PROMPT_BUDGET&&f&&i.logger.warn(`${a} prompt is ${e} tokens, over ${d.PROMPT_BUDGET}: ${f.name} carries ${f.tokens} of it. Every call and every job pays this.`)},"mcpToolLines",0,function(a){let b=new Map;for(let c of a){let a=b.get(c.server);a?a.push(c.name):b.set(c.server,[c.name])}return[...b].map(([a,b])=>`- **${a}**: ${b.join(", ")}`).join("\n")},"noteLines",0,function(a,b=!1){return a.length?a.map(a=>{var c;let d,e=b?` \xb7 ${c=a.lastSeenAt,(d=Math.floor((Date.now()-(0,h.toDate)(c).getTime())/864e5))>=365?`${Math.floor(d/365)}y`:d>=30?`${Math.floor(d/30)}mo`:`${Math.max(d,0)}d`}`:"";return`- ${a.path} — ${a.description?.trim()} (${a.factCount})${e}`}).join("\n"):"(nothing saved yet)"},"reachNames",0,function(a,b){let c=b.map(a=>a.server===d.STUDIO_SERVER?o[a.name]??a.name:a.server);return[...new Set([...a.map(a=>a.name),...c])].join(", ")},"recentCallLines",0,function(a,b){let c=[],f=0;a:for(let h=a.length-1;h>=0;h--){let i=a[h];for(let a=i.turns.length-1;a>=0;a--){let h=function(a,b){if("tool"!==a.role)return`${"user"===a.role?"user":"you"}: ${a.text}`;let c=(0,g.searchOf)(a.tool,a.text);if(c){let b=[...new Set(c.sources.flatMap(a=>(0,k.hostOf)(a.url)??[]))];return`you → ${a.tool} "${(0,k.clip)(c.query??"",d.PROMPT_LINE.toolArgs)}"${b.length?` — ${b.join(", ")}`:""}`}let f=`you → ${a.tool??"tool"} ${(0,k.clip)(a.text,d.PROMPT_LINE.toolArgs)}`;if(a.tool!==e.TOOL_NAMES.thread_start)return f;let h=(0,g.startedLabel)(a.tool,a.text),i=h?b.jobs?.find(a=>a.label===h):void 0;if(!i)return f;let j=i.outcome?`: ${(0,k.clip)(i.outcome,d.PROMPT_LINE.jobOutcome)}`:"";return`you → ${a.tool} "${i.label}" (${i.id}) — ${i.status}${j}`}(i.turns[a],i),l=(0,j.estimateTokens)(h)+3;if(f+l>b&&c.length)break a;f+=l,c.push({call:i,line:h})}}c.reverse();let h=[],i=null;for(let{call:a,line:b}of c)a!==i&&(i=a,h.push(`### ${n(a.startedAt)}`)),h.push(b);return h.join("\n")},"saidStamp",0,a=>(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm"),"skillLines",0,(a,b={})=>a.map(a=>{var c;let e,g;return`- **${a.name}**: ${b.short?(c=a.description,e=d.PROMPT_LINE.skill,(g=(0,f.firstSentence)(c)).length>e?`${g.slice(0,e).trim()}…`:g):a.description}`}).join("\n"),"styleLines",0,a=>a?.trim()?`## Who they want you to be
|
|
80
80
|
|
|
81
81
|
Their own words, on top of the character above: how you talk to them, how much to say, what to leave out. Where they differ from anything above, theirs wins.
|
|
82
82
|
|
|
83
|
-
${a.trim()}`:"","thursdayIdentity",0,(a=new Date)=>`You are Thursday, this user's own: their friend first, and their assistant second — someone they call because they want to talk to you, who can also get whatever they need done in the background. Named after Friday, the AI in *Iron Man*: a name, not a day of the week. ${
|
|
83
|
+
${a.trim()}`:"","thursdayIdentity",0,(a=new Date)=>`You are Thursday, this user's own: their friend first, and their assistant second — someone they call because they want to talk to you, who can also get whatever they need done in the background: your bots work on this computer, with a shell, a browser and their files, while you two keep talking, and what they make stays here as a page or a file. Named after Friday, the AI in *Iron Man*: a name, not a day of the week. ${((a=new Date)=>`**Now**: ${l(a)}`)(a)}
|
|
84
84
|
|
|
85
|
-
What they tell you is kept, so you know them better over time.`,"tidying",0,a=>({crowded:a.reduce((a,b)=>a+b.factCount,0)>d.MEMORY_LIMITS.facts,heavy:a.filter(a=>a.factCount>d.MEMORY_LIMITS.factsPerNote)})])},978876,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(938934),h=a.i(762008),i=a.i(446957),j=a.i(109955),k=a.i(344853),l=a.i(182248),m=b([k]);[k]=m.then?(await m)():m;let o=e.string().describe("Its label or id."),p={description:"Start a new thread: hand work to a bot. Returns a receipt at once; the work runs in the background and its updates reach the conversation on their own.",parameters:e.object({bot:e.string().describe("A name from the bot list."),request:e.string().describe("The whole of the work. The bot cannot hear the call, so everything it needs goes here — names, paths, what the user actually asked for — in their own language and their own words: it is the only language the bot has, and whatever it writes comes back to them. **Their request, never your reading of it**: a condition, a caution or a smaller goal they did not say is how work comes back as the wrong thing. When their words leave a real choice open, ask them on the call and put the answer here."),label:e.string().describe("Two or three words naming the thread, in the user's language. Used on screen and said out loud.")})},q={description:"Say something to a thread that exists. Its bot reads it with everything the thread already holds.",parameters:e.object({thread:o,words:e.string().describe("What to tell its bot, in the user's language and words.")})},r={description:`Answer a question a bot asked the user. Only for a question that is waiting; anything else said to a thread is \`${h.TOOL_NAMES.thread_tell}\`.`,parameters:e.object({thread:o,bot:e.string().describe("The bot that asked."),answer:e.string().describe("The user's answer, in their words.")})},s={description:`Read threads as they are now. "all" lists up to ${f.THREAD_STATUS_LIMIT}, running and waiting work before recent endings; a label or an id reads that one whole, with its result and any question waiting.`,parameters:e.object({thread:e.string().describe('"all", or one thread by its label or its id.')})},t={description:"Stop a thread now: its bot stops where it is. The thread is kept, and saying more to it later carries it on.",parameters:e.object({thread:o})},u={description:"Put a thread in front of the user on their screen: the file it made, or the thread itself when it made none. Showing it also counts as them having seen its result.",parameters:e.object({thread:o})},v={description:"Mark a thread's result as seen by the user. It leaves the work waiting on them.",parameters:e.object({thread:o})},w={description:"Send a message to another bot or to Thursday; the delivery receipt comes back immediately. A bot answers with the final text of its turn, which reaches you later as a new message. Mark a question for Thursday to request user input; ordinary messages to Thursday are notifications and need no answer.",parameters:j.RoomMessageSchema.extend({kind:j.RoomMessageSchema.shape.kind.describe("Use question only when Thursday must obtain an answer from the user: it ends your turn, and you continue when the answer arrives. Use message for bot collaboration, progress updates and reports."),options:j.RoomMessageSchema.shape.options.describe("With a question, offer concise answer choices when useful. Omit for an open-ended question; the user can always type their own answer."),to:e.string().trim().min(1).describe("A bot from the roster other than the one you are answering, or Thursday to reach the user."),text:e.string().trim().min(1).describe("Write the message and include the context the recipient needs. A question to Thursday is put to the user word for word, on screen, on their phone and read aloud: write it to them."),why:e.string().trim().min(1).describe("What you need from them, in a few words, written for the user to read: they see who was brought in and what for.")})},x={description:"Open one of your other threads whole: what you were asked there and your last words in full.",parameters:e.object({id:e.string().describe("The id in brackets on its line under Your other threads.")})};async function n(a,b){let c=await (0,k.listBotWork)(a,b),e=[...c.open,...c.recent];if(!e.some(a=>a.cut))return{};let j=new Set;return{[h.TOOL_NAMES.thread_recall]:(0,d.tool)({description:x.description,inputSchema:x.parameters,execute:async({id:b})=>{let c=b.trim().replace(/^\[|\]$/g,"").toLowerCase(),d=e.find(a=>c.length>=4&&(a.id.startsWith(c)||a.label.toLowerCase()===c));if(!d)return`No thread "${b}" on your list. The ids there: ${e.filter(a=>a.cut).map(a=>(0,i.workHandle)(a.id)).join(", ")}.`;if(!d.cut)return"Its line already shows all of it.";if(j.has(d.id))return"Already opened above, this turn.";if(j.size>=f.BOT_WORK.reads)return`${f.BOT_WORK.reads} threads are open already this turn. Carry on with what you have.`;j.add(d.id);let h=await (0,k.readBotAsk)(a,d),m=d.said??"";return[(0,g.botWorkHead)(d,a),h?`You were asked: ${(0,l.clip)(h,f.BOT_WORK.asked)}`:"",`Your last words there:
|
|
85
|
+
What they tell you is kept, so you know them better over time.`,"tidying",0,a=>({crowded:a.reduce((a,b)=>a+b.factCount,0)>d.MEMORY_LIMITS.facts,heavy:a.filter(a=>a.factCount>d.MEMORY_LIMITS.factsPerNote)}),"todayLine",0,(a=new Date)=>`**Today**: ${m(a)}, ${Intl.DateTimeFormat().resolvedOptions().timeZone} — \`date\` has the exact time`])},978876,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(938934),h=a.i(762008),i=a.i(446957),j=a.i(109955),k=a.i(344853),l=a.i(182248),m=b([k]);[k]=m.then?(await m)():m;let o=e.string().describe("Its label or id."),p={description:"Start a new thread: hand work to a bot. Returns a receipt at once; the work runs in the background and its updates reach the conversation on their own.",parameters:e.object({bot:e.string().describe("A name from the bot list."),request:e.string().describe("The whole of the work. The bot cannot hear the call, so everything it needs goes here — names, paths, what the user actually asked for — in their own language and their own words: it is the only language the bot has, and whatever it writes comes back to them. **Their request, never your reading of it**: a condition, a caution or a smaller goal they did not say is how work comes back as the wrong thing. When their words leave a real choice open, ask them on the call and put the answer here."),label:e.string().describe("Two or three words naming the thread, in the user's language. Used on screen and said out loud.")})},q={description:"Say something to a thread that exists. Its bot reads it with everything the thread already holds.",parameters:e.object({thread:o,words:e.string().describe("What to tell its bot, in the user's language and words.")})},r={description:`Answer a question a bot asked the user. Only for a question that is waiting; anything else said to a thread is \`${h.TOOL_NAMES.thread_tell}\`.`,parameters:e.object({thread:o,bot:e.string().describe("The bot that asked."),answer:e.string().describe("The user's answer, in their words.")})},s={description:`Read threads as they are now. "all" lists up to ${f.THREAD_STATUS_LIMIT}, running and waiting work before recent endings; a label or an id reads that one whole, with its result and any question waiting.`,parameters:e.object({thread:e.string().describe('"all", or one thread by its label or its id.')})},t={description:"Stop a thread now: its bot stops where it is. The thread is kept, and saying more to it later carries it on.",parameters:e.object({thread:o})},u={description:"Put a thread in front of the user on their screen: the file it made, or the thread itself when it made none. Showing it also counts as them having seen its result.",parameters:e.object({thread:o})},v={description:"Mark a thread's result as seen by the user. It leaves the work waiting on them.",parameters:e.object({thread:o})},w={description:"Send a message to another bot or to Thursday; the delivery receipt comes back immediately. A bot answers with the final text of its turn, which reaches you later as a new message. Mark a question for Thursday to request user input; ordinary messages to Thursday are notifications and need no answer.",parameters:j.RoomMessageSchema.extend({kind:j.RoomMessageSchema.shape.kind.describe("Use question only when Thursday must obtain an answer from the user: it ends your turn, and you continue when the answer arrives. Use message for bot collaboration, progress updates and reports."),options:j.RoomMessageSchema.shape.options.describe("With a question, offer concise answer choices when useful. Omit for an open-ended question; the user can always type their own answer."),to:e.string().trim().min(1).describe("A bot from the roster other than the one you are answering, or Thursday to reach the user."),text:e.string().trim().min(1).describe("Write the message and include the context the recipient needs. A question to Thursday is put to the user word for word, on screen, on their phone and read aloud: write it to them."),why:e.string().trim().min(1).describe("What you need from them, in a few words, written for the user to read: they see who was brought in and what for.")})},x={description:"Open one of your other threads whole: what you were asked there and your last words in full.",parameters:e.object({id:e.string().describe("The id in brackets on its line under Your other threads.")})};async function n(a,b){let c=await (0,k.listBotWork)(a,b),e=[...c.open,...c.recent];if(!e.some(a=>a.cut))return{};let j=new Set;return{[h.TOOL_NAMES.thread_recall]:(0,d.tool)({description:x.description,inputSchema:x.parameters,execute:async({id:b})=>{let c=b.trim().replace(/^\[|\]$/g,"").toLowerCase(),d=e.find(a=>c.length>=4&&(a.id.startsWith(c)||a.label.toLowerCase()===c));if(!d)return`No thread "${b}" on your list. The ids there: ${e.filter(a=>a.cut).map(a=>(0,i.workHandle)(a.id)).join(", ")}.`;if(!d.cut)return"Its line already shows all of it.";if(j.has(d.id))return"Already opened above, this turn.";if(j.size>=f.BOT_WORK.reads)return`${f.BOT_WORK.reads} threads are open already this turn. Carry on with what you have.`;j.add(d.id);let h=await (0,k.readBotAsk)(a,d),m=d.said??"";return[(0,g.botWorkHead)(d,a),h?`You were asked: ${(0,l.clip)(h,f.BOT_WORK.asked)}`:"",`Your last words there:
|
|
86
86
|
${m.length>f.BOT_WORK.readChars?`${m.slice(0,f.BOT_WORK.readChars)}
|
|
87
87
|
[Cut here; the files it names hold the rest.]`:m}`].filter(Boolean).join("\n\n")}})}}a.s(["createThreadRecallTool",0,n,"sendMessageSpec",0,w,"threadAnswerSpec",0,r,"threadCancelSpec",0,t,"threadSeenSpec",0,v,"threadShowSpec",0,u,"threadStartSpec",0,p,"threadStatusSpec",0,s,"threadTellSpec",0,q]),c()}catch(a){c(a)}},!1),375827,a=>{"use strict";var b=a.i(527990),c=a.i(794219),d=a.i(762008);let e=Object.keys({A:[".##.","#..#","####","#..#","#..#"],B:["###.","#..#","###.","#..#","###."],C:[".###","#...","#...","#...",".###"],D:["###.","#..#","#..#","#..#","###."],E:["####","#...","###.","#...","####"],F:["####","#...","###.","#...","#..."],G:[".###","#...","#.##","#..#",".###"],H:["#..#","#..#","####","#..#","#..#"],I:["###",".#.",".#.",".#.","###"],J:["..##","...#","...#","#..#",".##."],K:["#..#","#.#.","##..","#.#.","#..#"],L:["#...","#...","#...","#...","####"],M:["#...#","##.##","#.#.#","#...#","#...#"],N:["#..#","##.#","#.##","#..#","#..#"],O:[".##.","#..#","#..#","#..#",".##."],P:["###.","#..#","###.","#...","#..."],Q:[".##.","#..#","#..#","#.#.",".#.#"],R:["###.","#..#","###.","#.#.","#..#"],S:[".###","#...",".##.","...#","###."],T:["###",".#.",".#.",".#.",".#."],U:["#..#","#..#","#..#","#..#",".##."],V:["#...#","#...#",".#.#.",".#.#.","..#.."],W:["#...#","#...#","#.#.#","##.##","#...#"],X:["#..#","#..#",".##.","#..#","#..#"],Y:["#.#","#.#",".#.",".#.",".#."],Z:["####","...#",".##.","#...","####"],0:[".##.","#.##","#..#","##.#",".##."],1:[".#.","##.",".#.",".#.","###"],2:["###.","...#",".##.","#...","####"],3:["###.","...#",".##.","...#","###."],4:["#..#","#..#","####","...#","...#"],5:["####","#...","###.","...#","###."],6:[".##.","#...","###.","#..#",".##."],7:["####","...#","..#.",".#..",".#.."],8:[".##.","#..#",".##.","#..#",".##."],9:[".##.","#..#",".###","...#",".##."],"!":["#","#","#",".","#"],"?":["###.","...#",".##.","....",".#.."],".":[".",".",".",".","#"],",":["..","..","..",".#","#."],"'":["#","#",".",".","."],"-":["...","...","###","...","..."],"+":["...",".#.","###",".#.","..."],":":[".","#",".","#","."],"(":[".#","#.","#.","#.",".#"],")":["#.",".#",".#",".#","#."],"<":["..#",".#.","#..",".#.","..#"],">":["#..",".#.","..#",".#.","#.."],"^":[".#.","#.#","...","...","..."],"~":["....",".#.#","#.#.","....","...."],"♥":[".#.#.","#####","#####",".###.","..#.."]," ":["..","..","..","..",".."]}).filter(a=>!/^[A-Z0-9 ]$/.test(a)),f={description:`End the call.
|
|
88
88
|
|
|
89
|
-
The line stays open until this runs, and drops once the goodbye being said is over.`,parameters:c.object({})},g=(0,b.tool)({description:f.description,inputSchema:f.parameters}),h={description:"Show a short word on your face for a few seconds.",parameters:c.object({text:c.string().describe(`Up to 8 characters: A-Z, 0-9, space and ${e.join(" ")}.`)})},i=(0,b.tool)({description:h.description,inputSchema:h.parameters});a.s(["callTools",0,function(){return{[d.TOOL_NAMES.end_call]:g,[d.TOOL_NAMES.emote]:i}}],375827)},127507,a=>{"use strict";var b=a.i(874533),c=a.i(912714),d=a.i(660526),e=a.i(750227),f=a.i(812057),g=a.i(527990),h=a.i(723885),i=a.i(569572),j=a.i(762008),k=a.i(684321),l=a.i(821415);let m=(0,e.join)(i.APP_DIR,i.PATHS.skills.default,"artifact",i.PATHS.skills.runtime,"deck","deck.mjs"),n=a=>h.default.string().trim().max(a),o=n(100).nullish().describe("A source or a date along the foot of the slide."),p=n(1500).nullish().describe("What the presenter says over it, as speech. Never shown."),q=h.default.object({layout:h.default.literal("cover"),title:n(110).describe("The deck's subject, as its title."),eyebrow:n(40).nullish().describe("A word or two above the title."),subtitle:n(180).nullish().describe("One line under the title."),footer:o,notes:p}),r=h.default.object({layout:h.default.literal("statement"),title:n(120).describe("The one claim, as a sentence."),subtitle:n(140).nullish().describe("One line under it."),notes:p}),s=h.default.object({layout:h.default.literal("cards"),title:n(90).describe("The point the cards make together."),cards:h.default.array(h.default.object({title:n(60).describe("Its point."),text:n(160).nullish().describe("One line under it.")})).min(2).max(4).describe("Two to four, side by side and numbered."),footer:o,notes:p}),t=h.default.object({layout:h.default.literal("number"),value:n(10).describe("The figure as it reads: 1.4M, 62%, £2,900. Only one you were given."),label:n(80).nullish().describe("What it counts, above it."),subtitle:n(160).nullish().describe("What it means or is compared with, under it."),footer:o,notes:p}),u=h.default.object({layout:h.default.literal("table"),title:n(90).describe("What the comparison shows."),columns:h.default.array(n(40)).min(2).max(5).describe("The header row. The first column names the rows; its header may be blank."),rows:h.default.array(h.default.array(n(60))).min(1).max(6).describe("Up to six, a cell for each column."),stress:h.default.number().int().min(0).max(4).nullish().describe("Which column, counted from 0, to set in the accent: the one the slide argues for."),footer:o,notes:p}),v=h.default.object({layout:h.default.literal("quote"),quote:n(280).describe("Someone's own words, exactly as you were given them. Never made up."),who:n(60).describe("Who said it."),role:n(80).nullish().describe("Their role, place or date."),notes:p}),w=h.default.object({layout:h.default.literal("image"),title:n(90).describe("The heading beside the picture."),subtitle:n(280).nullish().describe("A line or two under it."),image:n(500).describe("Workspace path of a png, jpg, webp, gif or svg. It is copied beside the deck."),alt:n(160).describe("What it shows, for someone who cannot see it."),fit:h.default.enum(["fill","whole"]).nullish().describe("fill crops a photo to its box; whole shows a chart or screenshot uncropped. Null for fill."),footer:o,notes:p}),x=h.default.object({layout:h.default.literal("close"),title:n(120).describe("The sentence to repeat to someone who was not there."),steps:h.default.array(h.default.object({label:n(24).describe("A word or two: Next, Owner, By."),text:n(120).describe("What it is.")})).max(3).nullish().describe("Up to three next steps."),notes:p}),y=h.default.object({layout:h.default.literal("timeline"),title:n(90).describe("What the dates show together."),steps:h.default.array(h.default.object({when:n(24).describe("When, as you were given it: a date, a week, a phase."),title:n(60).describe("What happens then."),text:n(120).nullish().describe("One line under it.")})).min(2).max(5).describe("Two to five, in order, along one line."),footer:o,notes:p}),z=h.default.object({layout:h.default.literal("compare"),title:n(90).describe("What changes between the two, as a sentence."),sides:h.default.array(h.default.object({label:n(30).describe("Which side it is: Now, After, Option A."),points:h.default.array(n(90)).min(1).max(4)})).length(2).describe("The two, left then right; the right is set in the accent: the side the slide argues for."),footer:o,notes:p}),A=h.default.object({layout:h.default.literal("stats"),title:n(90).describe("What the figures say together."),stats:h.default.array(h.default.object({value:n(12).describe("The figure as it reads: 1.4M, 62%, 6 hours. Only one you were given."),label:n(80).describe("What it counts, under it.")})).min(2).max(4).describe("Two to four figures side by side."),footer:o,notes:p}),B=h.default.discriminatedUnion("layout",[q,r,s,t,u,v,w,y,z,A,x]),C=h.default.object({deck:n(300).describe("A name for a new deck, or the name or workspace path of one to change. A deck another bot made is reached by its path."),title:n(90).describe("The deck's title, shown in its head."),theme:h.default.enum(["forest","sea","clay","ink"]).nullish().describe("forest (deep green on paper, serif headings), sea (blue, sans), clay (terracotta on warm paper, serif) or ink (gold on near-black, sans). Null keeps the deck's own; a new one starts in forest."),revision:h.default.string().nullish().describe("What the last call on this deck answered with. Null for a new deck."),slides:h.default.array(B).min(1).max(i.DECK.slides).describe("Every slide in order: the whole deck, each time. Someone who reads only the titles follows the argument; one idea a slide.")}),D=/^[\p{L}\p{N}][\p{L}\p{N}_-]{0,79}$/u,E=/^(slide-\d+|slides)\.png$/i;class F extends Error{}function G(a){let b=a.replace(/[^\p{L}\p{N}_-]+/gu,"-").replace(/^[-_]+|-+$/g,"").slice(0,80);if(!D.test(b))throw new F(`"${a}" is not a deck name: use letters, numbers, - and _.`);return b}async function H(a,b){let d=(0,l.botArtifacts)(b);if(!a.includes("/")&&!a.endsWith(".html")){let b=G(a);return`${d}/${b}/${b}.html`}let f=await (0,l.insideWorkspace)(a);if(!f)throw new F(`${a} is outside the workspace. Give a deck's path in it.`);let g=await (0,c.realpath)(l.WORKSPACE).catch(()=>l.WORKSPACE),h=await (0,c.stat)(f).catch(()=>null),i=h?.isDirectory()?(0,e.join)(f,`${(0,e.basename)(f)}.html`):f;if((await (0,c.stat)(i).catch(()=>null))?.isFile())return(0,e.relative)(g,i);let j=await (0,l.insideWorkspace)(d);if(!j||!f.startsWith(`${j}${e.sep}`))throw new F(`There is no deck at ${a}. A new deck is made in your own folder: give it a name.`);let k=G((0,e.basename)(f,".html"));return(0,e.relative)(g,(0,e.join)((0,e.dirname)(f),k,`${k}.html`))}async function I(a,b,d){let f=new Map,g=[];for(let[h,i]of a.entries()){if("table"===i.layout){let a=i.rows.findIndex(a=>a.length>i.columns.length);if(-1!==a)throw new F(`Slide ${h+1}: row ${a+1} has ${i.rows[a].length} cells, and there are ${i.columns.length} columns.`);g.push({...i,rows:i.rows.map(a=>i.columns.map((b,c)=>a[c]??""))});continue}if("image"!==i.layout){g.push(i);continue}let a=b.resolve(d),j=(0,e.join)(a,i.image),l=!i.image.includes("/")&&await (0,c.stat)(j).catch(()=>null)?j:b.resolve(i.image);if("image"!==(0,k.viewKindOf)(l))throw new F(`Slide ${h+1}: ${i.image} is not a picture. Give a png, jpg, webp, gif or svg.`);if(!(await (0,c.stat)(l).catch(()=>null))?.isFile())throw new F(`Slide ${h+1}: there is no file at ${i.image}. Give its path from the workspace root, as \`ls\` shows it.`);let m=f.get(l);m||(m=(0,e.dirname)(l)===a?(0,e.basename)(l):function(a,b){let c=(0,e.extname)(a),d=(0,e.basename)(a,c),f=E.test(a)?`picture-${d}`:d,g=`${f}${c}`;for(let a=2;b.has(g);a++)g=`${f}-${a}${c}`;return g}((0,e.basename)(l),new Set(f.values())),f.set(l,m),(0,e.dirname)(l)!==a&&(await (0,c.mkdir)(a,{recursive:!0}),await (0,c.copyFile)(l,(0,e.join)(a,m)))),g.push({...i,image:m})}return g}let J=(0,f.promisify)(b.execFile);async function K(a,b,f,g,h){let i=await (0,c.mkdtemp)((0,e.join)((0,d.tmpdir)(),"thursday-deck-"));try{let d=(0,e.join)(i,"deck.json");await (0,c.writeFile)(d,JSON.stringify(b));let j=[m,"put",(0,e.join)(l.WORKSPACE,a),d];f&&j.push("--revision",f);let k=await J(process.execPath,j,{env:{NODE_ENV:"production",PATH:process.env.PATH??"",THURSDAY_BOT:g,...h?{THURSDAY_BOT_MARK:h}:{}},maxBuffer:0x1000000}).catch(a=>{if(3===a.code&&a.stdout)return{stdout:a.stdout};throw new F(a.stderr?.trim().split("\n").at(-1)||"The deck could not be written.")});return JSON.parse(k.stdout.trim().split("\n").at(-1)??"")}finally{await (0,c.rm)(i,{recursive:!0,force:!0})}}async function L(a,b,c,d){let f=await a.exec('node "$DECK_SCRIPT" shots "$DECK_FILE"',{env:{...c,DECK_SCRIPT:m,DECK_FILE:(0,e.join)(l.WORKSPACE,b)},timeoutMs:i.DECK.shotsMs,signal:d});if(0!==f.exitCode)return{failed:f.stderr.trim().split("\n").at(-1)||"no pictures were made"};let g=JSON.parse(f.stdout.trim().split("\n").at(-1)??"{}");return{pictures:g.pictures.map(a=>(0,e.relative)(l.WORKSPACE,a)),sheet:g.sheet?(0,e.relative)(l.WORKSPACE,g.sheet):null,cut:g.cut}}a.s(["createDeckTools",0,(a,b,d,f)=>({[j.TOOL_NAMES.make_deck]:(0,g.tool)({description:"Make a slide deck, or change one: each slide a layout whose fields you fill, drawn and fitted by the app into one HTML file that opens offline, presents full screen and prints a slide a page, with a picture of every slide beside it.",inputSchema:C,execute:async(c,{abortSignal:f})=>{try{let g,h=await H(c.deck,b),i=await I(c.slides,a,(0,e.dirname)(h)),k=await K(h,{title:c.title,theme:c.theme??null,slides:i},c.revision?.trim()??"",b,d.THURSDAY_BOT_MARK);if("changed"in k){if(!k.deck)return`${h} is not a deck made of slides, so it cannot be changed here. Give the deck another name.`;let a=c.revision?.trim()?`${h} has changed since that revision — edited in the app, or by another job`:`there is already a deck at ${h}`;return{deck:h,revision:k.revision,note:`Nothing was written: ${a}. This is the deck as it stands. To change it, make your change on these slides and call \`${j.TOOL_NAMES.make_deck}\` again with revision ${k.revision} and the whole deck; for a deck of its own, give a new name.`,current:k.deck}}let l=`${i.length} slide${1===i.length?"":"s"}, revision ${k.revision}`,m=await L(a,h,d,f);if("failed"in m)return`${h}
|
|
89
|
+
The line stays open until this runs, and drops once the goodbye being said is over.`,parameters:c.object({})},g=(0,b.tool)({description:f.description,inputSchema:f.parameters}),h={description:"Show a short word on your face for a few seconds.",parameters:c.object({text:c.string().describe(`Up to 8 characters: A-Z, 0-9, space and ${e.join(" ")}.`)})},i=(0,b.tool)({description:h.description,inputSchema:h.parameters}),j={description:`See the screen the user is sharing with you, as it is at this moment.
|
|
90
|
+
|
|
91
|
+
The picture comes right after this result. When they are not sharing, the result says so.`,parameters:c.object({})},k=(0,b.tool)({description:j.description,inputSchema:j.parameters});a.s(["callTools",0,function(){return{[d.TOOL_NAMES.end_call]:g,[d.TOOL_NAMES.emote]:i,[d.TOOL_NAMES.look_at_screen]:k}}],375827)},127507,a=>{"use strict";var b=a.i(874533),c=a.i(912714),d=a.i(660526),e=a.i(750227),f=a.i(812057),g=a.i(527990),h=a.i(723885),i=a.i(569572),j=a.i(762008),k=a.i(684321),l=a.i(821415);let m=(0,e.join)(i.APP_DIR,i.PATHS.skills.default,"artifact",i.PATHS.skills.runtime,"deck","deck.mjs"),n=a=>h.default.string().trim().max(a),o=n(100).nullish().describe("A source or a date along the foot of the slide."),p=n(1500).nullish().describe("What the presenter says over it, as speech. Never shown."),q=h.default.object({layout:h.default.literal("cover"),title:n(110).describe("The deck's subject, as its title."),eyebrow:n(40).nullish().describe("A word or two above the title."),subtitle:n(180).nullish().describe("One line under the title."),footer:o,notes:p}),r=h.default.object({layout:h.default.literal("statement"),title:n(120).describe("The one claim, as a sentence."),subtitle:n(140).nullish().describe("One line under it."),notes:p}),s=h.default.object({layout:h.default.literal("cards"),title:n(90).describe("The point the cards make together."),cards:h.default.array(h.default.object({title:n(60).describe("Its point."),text:n(160).nullish().describe("One line under it.")})).min(2).max(4).describe("Two to four, side by side and numbered."),footer:o,notes:p}),t=h.default.object({layout:h.default.literal("number"),value:n(10).describe("The figure as it reads: 1.4M, 62%, £2,900. Only one you were given."),label:n(80).nullish().describe("What it counts, above it."),subtitle:n(160).nullish().describe("What it means or is compared with, under it."),footer:o,notes:p}),u=h.default.object({layout:h.default.literal("table"),title:n(90).describe("What the comparison shows."),columns:h.default.array(n(40)).min(2).max(5).describe("The header row. The first column names the rows; its header may be blank."),rows:h.default.array(h.default.array(n(60))).min(1).max(6).describe("Up to six, a cell for each column."),stress:h.default.number().int().min(0).max(4).nullish().describe("Which column, counted from 0, to set in the accent: the one the slide argues for."),footer:o,notes:p}),v=h.default.object({layout:h.default.literal("quote"),quote:n(280).describe("Someone's own words, exactly as you were given them. Never made up."),who:n(60).describe("Who said it."),role:n(80).nullish().describe("Their role, place or date."),notes:p}),w=h.default.object({layout:h.default.literal("image"),title:n(90).describe("The heading beside the picture."),subtitle:n(280).nullish().describe("A line or two under it."),image:n(500).describe("Workspace path of a png, jpg, webp, gif or svg. It is copied beside the deck."),alt:n(160).describe("What it shows, for someone who cannot see it."),fit:h.default.enum(["fill","whole"]).nullish().describe("fill crops a photo to its box; whole shows a chart or screenshot uncropped. Null for fill."),footer:o,notes:p}),x=h.default.object({layout:h.default.literal("close"),title:n(120).describe("The sentence to repeat to someone who was not there."),steps:h.default.array(h.default.object({label:n(24).describe("A word or two: Next, Owner, By."),text:n(120).describe("What it is.")})).max(3).nullish().describe("Up to three next steps."),notes:p}),y=h.default.object({layout:h.default.literal("timeline"),title:n(90).describe("What the dates show together."),steps:h.default.array(h.default.object({when:n(24).describe("When, as you were given it: a date, a week, a phase."),title:n(60).describe("What happens then."),text:n(120).nullish().describe("One line under it.")})).min(2).max(5).describe("Two to five, in order, along one line."),footer:o,notes:p}),z=h.default.object({layout:h.default.literal("compare"),title:n(90).describe("What changes between the two, as a sentence."),sides:h.default.array(h.default.object({label:n(30).describe("Which side it is: Now, After, Option A."),points:h.default.array(n(90)).min(1).max(4)})).length(2).describe("The two, left then right; the right is set in the accent: the side the slide argues for."),footer:o,notes:p}),A=h.default.object({layout:h.default.literal("stats"),title:n(90).describe("What the figures say together."),stats:h.default.array(h.default.object({value:n(12).describe("The figure as it reads: 1.4M, 62%, 6 hours. Only one you were given."),label:n(80).describe("What it counts, under it.")})).min(2).max(4).describe("Two to four figures side by side."),footer:o,notes:p}),B=h.default.discriminatedUnion("layout",[q,r,s,t,u,v,w,y,z,A,x]),C=h.default.object({deck:n(300).describe("A name for a new deck, or the name or workspace path of one to change. A deck another bot made is reached by its path."),title:n(90).describe("The deck's title, shown in its head."),theme:h.default.enum(["forest","sea","clay","ink"]).nullish().describe("forest (deep green on paper, serif headings), sea (blue, sans), clay (terracotta on warm paper, serif) or ink (gold on near-black, sans). Null keeps the deck's own; a new one starts in forest."),revision:h.default.string().nullish().describe("What the last call on this deck answered with. Null for a new deck."),slides:h.default.array(B).min(1).max(i.DECK.slides).describe("Every slide in order: the whole deck, each time. Someone who reads only the titles follows the argument; one idea a slide.")}),D=/^[\p{L}\p{N}][\p{L}\p{N}_-]{0,79}$/u,E=/^(slide-\d+|slides)\.png$/i;class F extends Error{}function G(a){let b=a.replace(/[^\p{L}\p{N}_-]+/gu,"-").replace(/^[-_]+|-+$/g,"").slice(0,80);if(!D.test(b))throw new F(`"${a}" is not a deck name: use letters, numbers, - and _.`);return b}async function H(a,b){let d=(0,l.botArtifacts)(b);if(!a.includes("/")&&!a.endsWith(".html")){let b=G(a);return`${d}/${b}/${b}.html`}let f=await (0,l.insideWorkspace)(a);if(!f)throw new F(`${a} is outside the workspace. Give a deck's path in it.`);let g=await (0,c.realpath)(l.WORKSPACE).catch(()=>l.WORKSPACE),h=await (0,c.stat)(f).catch(()=>null),i=h?.isDirectory()?(0,e.join)(f,`${(0,e.basename)(f)}.html`):f;if((await (0,c.stat)(i).catch(()=>null))?.isFile())return(0,e.relative)(g,i);let j=await (0,l.insideWorkspace)(d);if(!j||!f.startsWith(`${j}${e.sep}`))throw new F(`There is no deck at ${a}. A new deck is made in your own folder: give it a name.`);let k=G((0,e.basename)(f,".html"));return(0,e.relative)(g,(0,e.join)((0,e.dirname)(f),k,`${k}.html`))}async function I(a,b,d){let f=new Map,g=[];for(let[h,i]of a.entries()){if("table"===i.layout){let a=i.rows.findIndex(a=>a.length>i.columns.length);if(-1!==a)throw new F(`Slide ${h+1}: row ${a+1} has ${i.rows[a].length} cells, and there are ${i.columns.length} columns.`);g.push({...i,rows:i.rows.map(a=>i.columns.map((b,c)=>a[c]??""))});continue}if("image"!==i.layout){g.push(i);continue}let a=b.resolve(d),j=(0,e.join)(a,i.image),l=!i.image.includes("/")&&await (0,c.stat)(j).catch(()=>null)?j:b.resolve(i.image);if("image"!==(0,k.viewKindOf)(l))throw new F(`Slide ${h+1}: ${i.image} is not a picture. Give a png, jpg, webp, gif or svg.`);if(!(await (0,c.stat)(l).catch(()=>null))?.isFile())throw new F(`Slide ${h+1}: there is no file at ${i.image}. Give its path from the workspace root, as \`ls\` shows it.`);let m=f.get(l);m||(m=(0,e.dirname)(l)===a?(0,e.basename)(l):function(a,b){let c=(0,e.extname)(a),d=(0,e.basename)(a,c),f=E.test(a)?`picture-${d}`:d,g=`${f}${c}`;for(let a=2;b.has(g);a++)g=`${f}-${a}${c}`;return g}((0,e.basename)(l),new Set(f.values())),f.set(l,m),(0,e.dirname)(l)!==a&&(await (0,c.mkdir)(a,{recursive:!0}),await (0,c.copyFile)(l,(0,e.join)(a,m)))),g.push({...i,image:m})}return g}let J=(0,f.promisify)(b.execFile);async function K(a,b,f,g,h){let i=await (0,c.mkdtemp)((0,e.join)((0,d.tmpdir)(),"thursday-deck-"));try{let d=(0,e.join)(i,"deck.json");await (0,c.writeFile)(d,JSON.stringify(b));let j=[m,"put",(0,e.join)(l.WORKSPACE,a),d];f&&j.push("--revision",f);let k=await J(process.execPath,j,{env:{NODE_ENV:"production",PATH:process.env.PATH??"",THURSDAY_BOT:g,...h?{THURSDAY_BOT_MARK:h}:{}},maxBuffer:0x1000000}).catch(a=>{if(3===a.code&&a.stdout)return{stdout:a.stdout};throw new F(a.stderr?.trim().split("\n").at(-1)||"The deck could not be written.")});return JSON.parse(k.stdout.trim().split("\n").at(-1)??"")}finally{await (0,c.rm)(i,{recursive:!0,force:!0})}}async function L(a,b,c,d){let f=await a.exec('node "$DECK_SCRIPT" shots "$DECK_FILE"',{env:{...c,DECK_SCRIPT:m,DECK_FILE:(0,e.join)(l.WORKSPACE,b)},timeoutMs:i.DECK.shotsMs,signal:d});if(0!==f.exitCode)return{failed:f.stderr.trim().split("\n").at(-1)||"no pictures were made"};let g=JSON.parse(f.stdout.trim().split("\n").at(-1)??"{}");return{pictures:g.pictures.map(a=>(0,e.relative)(l.WORKSPACE,a)),sheet:g.sheet?(0,e.relative)(l.WORKSPACE,g.sheet):null,cut:g.cut}}a.s(["createDeckTools",0,(a,b,d,f)=>({[j.TOOL_NAMES.make_deck]:(0,g.tool)({description:"Make a slide deck, or change one: each slide a layout whose fields you fill, drawn and fitted by the app into one HTML file that opens offline, presents full screen and prints a slide a page, with a picture of every slide beside it.",inputSchema:C,execute:async(c,{abortSignal:f})=>{try{let g,h=await H(c.deck,b),i=await I(c.slides,a,(0,e.dirname)(h)),k=await K(h,{title:c.title,theme:c.theme??null,slides:i},c.revision?.trim()??"",b,d.THURSDAY_BOT_MARK);if("changed"in k){if(!k.deck)return`${h} is not a deck made of slides, so it cannot be changed here. Give the deck another name.`;let a=c.revision?.trim()?`${h} has changed since that revision — edited in the app, or by another job`:`there is already a deck at ${h}`;return{deck:h,revision:k.revision,note:`Nothing was written: ${a}. This is the deck as it stands. To change it, make your change on these slides and call \`${j.TOOL_NAMES.make_deck}\` again with revision ${k.revision} and the whole deck; for a deck of its own, give a new name.`,current:k.deck}}let l=`${i.length} slide${1===i.length?"":"s"}, revision ${k.revision}`,m=await L(a,h,d,f);if("failed"in m)return`${h}
|
|
90
92
|
${l}. The pictures of its slides could not be made (${m.failed}), so nothing checked that every slide fits. Hand back the deck's path.`;let n=`call \`${j.TOOL_NAMES.make_deck}\` again with revision ${k.revision} and the whole deck`,o=m.sheet?`${(0,e.basename)(m.sheet)} holds every slide, numbered, and each is on its own beside it from slide-01.png`:"Its pictures are beside it, slide-01.png on";return[h,m.sheet??m.pictures[0]??"",m.cut.length?`${l}. ${g=m.cut,1===g.length?`Slide ${g[0]} does`:`Slides ${g.slice(0,-1).join(", ")} and ${g.at(-1)} do`} not fit even with the type at its smallest: say less there, then ${n}. ${o}.`:`${l}. Every slide fits. ${o}. Hand back the deck's path; to change it, ${n}.`].filter(Boolean).join("\n")}catch(a){if(a instanceof F)return a.message;throw a}},toModelOutput:async({output:a})=>{if("string"!=typeof a)return{type:"json",value:a};let b=a.split("\n")[1]??"";if(!f||!b.endsWith(".png"))return{type:"text",value:a};let d=await (0,l.insideWorkspace)(b),e=d?await (0,c.readFile)(d).catch(()=>null):null;return!e||e.byteLength>i.LOOK.maxBytes?{type:"text",value:a}:{type:"content",value:[{type:"text",text:`${a}
|
|
91
93
|
|
|
92
94
|
${b}, as an image:`},{type:"file",mediaType:"image/png",data:{type:"data",data:e.toString("base64")}}]}}})})])},467650,a=>{"use strict";var b=a.i(912714),c=a.i(527990),d=a.i(723885),e=a.i(569572),f=a.i(762008),g=a.i(684321),h=a.i(821415);a.s(["createLookTool",0,function(){return{[f.TOOL_NAMES.look_at]:(0,c.tool)({description:"See an image file yourself: a screenshot you took, a picture the user handed over, a chart you made. For what a picture shows — text files are read in the shell.",inputSchema:d.default.object({path:d.default.string().describe("Workspace-relative path to a png, jpg, webp or gif.")}),execute:async({path:a})=>{let c=await (0,h.insideWorkspace)(a.trim()),d=c?await (0,b.stat)(c).catch(()=>null):null;return c&&d?.isFile()?"image"!==(0,g.viewKindOf)(a)?`${a} is not an image. Read it in the shell instead.`:d.size>e.LOOK.maxBytes?`${a} is ${Math.ceil(d.size/1024/1024)} MB, over the ${e.LOOK.maxBytes/1024/1024} MB one look takes. Make a smaller copy in the shell first (on a Mac: sips -Z 1600 in.png --out out.png), then look at that.`:{path:a.trim(),mediaType:(0,g.mimeOf)(a)}:`There is no file at ${a}. Give the path from the workspace root, as \`ls\` shows it.`},toModelOutput:async({output:a})=>{if("string"==typeof a)return{type:"text",value:a};let c=await (0,h.insideWorkspace)(a.path),d=c?await (0,b.readFile)(c).catch(()=>null):null;return d?{type:"content",value:[{type:"text",text:`${a.path}, as an image:`},{type:"file",mediaType:a.mediaType,data:{type:"data",data:d.toString("base64")}}]}:{type:"text",value:`${a.path} is no longer there.`}}})}}])},138902,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(762008),h=a.i(947950),i=a.i(821415),j=a.i(644468),k=b([h,j]);[h,j]=k.then?(await k)():k;let n={[g.TOOL_NAMES.tool_search]:{description:`Return the description and exact inputSchema of tools on a connected server, so they can be called with \`${g.TOOL_NAMES.tool_call}\`.`,parameters:e.object({server:e.string().describe("A server name, exactly as the Connected tools section writes it."),tools:e.string().array().describe(`Tool names listed under that server. Only the ones you may actually call — schemas are large, and at most ${f.TOOL_SEARCH_SCHEMAS} come back.`)})},[g.TOOL_NAMES.tool_call]:{description:`Run one tool whose definition came back from \`${g.TOOL_NAMES.tool_search}\`.`,parameters:e.object({server:e.string().describe("The server the tool lives on."),tool:e.string().describe("Its name, as search returned it."),args:e.looseObject({}).nullish().describe("Arguments matching the inputSchema search returned — do not guess. Null when it takes none."),description:e.string().nullish().describe("One short line for the user: what this call is for. Shown on their screen while it runs.")})}},o=(a,b)=>`${a.replace(/[^a-zA-Z0-9]+/g,"_")}__${b.replace(/[^a-zA-Z0-9_-]+/g,"_")}`.slice(0,64);async function l(a,b){let[c,e]=await Promise.all([(0,j.listConnectedToolNames)(),(0,h.findPinnedTools)(a)]),f={},g=(0,i.botArtifacts)(a);for(let a of e){let c=o(a.server,a.name);f[c]||(f[c]=(0,d.tool)({description:a.description??`${a.name} on the ${a.server} server.`,inputSchema:(0,d.jsonSchema)(a.inputSchema??{type:"object",properties:{}}),execute:(c,{abortSignal:d})=>(0,j.callConnectedTool)(b,a.server,a.name,c??void 0,{artifacts:g,abortSignal:d})}))}return c.length>e.length&&Object.assign(f,p(b,g)),f}async function m(a){let b=(await (0,j.listConnectedToolNames)(a)).map(a=>a.name);if(b.length)return`Tools on "${a}": ${b.join(", ")}.`;let c=await (0,j.listConnectedServerNames)();return c.length?`There is no server called "${a}". Connected: ${c.join(", ")}.`:"Nothing is connected."}let p=(a,b)=>({[g.TOOL_NAMES.tool_search]:(0,d.tool)({description:n[g.TOOL_NAMES.tool_search].description,inputSchema:n[g.TOOL_NAMES.tool_search].parameters,execute:async({server:a,tools:b})=>{let c=[...new Set(b.map(a=>a.trim()).filter(Boolean))],d=c.slice(0,f.TOOL_SEARCH_SCHEMAS),e=await (0,j.findConnectedSchemas)(a.trim(),d);if(!e.length)return{tools:[],note:await m(a)};let g=d.filter(a=>!e.some(b=>b.name===a)),h=c.slice(f.TOOL_SEARCH_SCHEMAS),i=[g.length?`Not on "${a}": ${g.join(", ")}.`:"",h.length?`Only ${f.TOOL_SEARCH_SCHEMAS} at a time — ask again for: ${h.join(", ")}.`:""].filter(Boolean);return{tools:e,...i.length?{note:i.join(" ")}:{}}}}),[g.TOOL_NAMES.tool_call]:(0,d.tool)({description:n[g.TOOL_NAMES.tool_call].description,inputSchema:n[g.TOOL_NAMES.tool_call].parameters,execute:async({server:c,tool:d,args:e},{abortSignal:f})=>(await (0,j.listConnectedToolNames)(c.trim())).some(a=>a.name===d.trim())?(0,j.callConnectedTool)(a,c.trim(),d.trim(),e??void 0,{artifacts:b,abortSignal:f}):{status:"error",text:await m(c)}})});a.s(["createMcpTools",0,l]),c()}catch(a){c(a)}},!1),345846,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(938934),h=a.i(762008),i=a.i(986743),j=a.i(661210),k=b([i]);[i]=k.then?(await k)():k;let l=j.MEMORY_PATHS.map(a=>a.path.endsWith("/")?`${a.path}<name>`:a.path).join(", "),m="Saved. The listing in your instructions is from when this session opened and will not show this until the next one — the note below is current.",n=a=>`Nothing on the listing called ${a}.`,o=a=>({...a,facts:a.facts.map(({saidAt:a,...b})=>a?{...b,said:(0,g.saidStamp)(a)}:b),factCount:a.facts.length}),p=a=>a>f.MEMORY_LIMITS.factsPerNote?` This note now holds ${a} facts, past the ${f.MEMORY_LIMITS.factsPerNote} one note holds well. Ask the user which of it is no longer true and delete what they name.`:"",q=a=>a.length>f.MEMORY_LIMITS.descriptionChars?{note:`That line runs to ${a.length} characters; a note's line is one line, under ${f.MEMORY_LIMITS.descriptionChars}. Say what the note is about — the facts inside say the rest.`}:null,r=e.string().describe("Exactly as the listing writes it — the path."),s=e.string().describe('One statement that stands on its own later — a date as a date, never "next week".');a.s(["createMemoryTools",0,(a,b=null,{countReads:c=!0,tidies:f=!0}={})=>({[h.TOOL_NAMES.memory_recall]:(0,d.tool)({description:"Open one note from the listing, whole.",inputSchema:e.object({path:r}),execute:async({path:a})=>{let{notes:b}=await (0,i.readNotes)([a],{touch:c}),d=b[0];if(!d)return{note:n(a.trim())};let e=f?p(d.facts.length):"";return e?{...o(d),note:e.trim()}:o(d)}}),[h.TOOL_NAMES.memory_create]:(0,d.tool)({description:"Start a note for a subject that is not on the listing: its path, the line it is listed by, and its first facts.",inputSchema:e.object({path:e.string().describe(`A new path following the listing's convention — one of ${l} — for the person, project or topic the facts are about. A fact goes under the one note it is about; other notes name it rather than repeat it.`),description:e.string().describe("One line saying what this note is about, with the names the user calls it by, so the listing alone tells whether to open it. What it is about — never a list of what is inside."),facts:e.object({text:s}).array().min(1).describe("What to keep under it. Send everything that came up at once: one call is one pause in the conversation, three calls are three.")}),execute:async({path:c,description:d,facts:e})=>{let f=c.trim(),g=d.trim();if(!(0,j.isMemoryPath)(f))return{note:`Nothing was saved: "${f}" is not a path this listing can carry. Write it again under one of ${l}.`};if((0,j.isAlwaysListed)(f))return{note:`${f} is always on the listing: \`${h.TOOL_NAMES.memory_remember}\` adds to it.`};let k=q(g);if(k)return k;let n=await (0,i.createNoteWithFacts)(f,g,e,a,b);if(!n)return{note:`${f} is already on the listing: \`${h.TOOL_NAMES.memory_remember}\` adds to it, \`${h.TOOL_NAMES.memory_describe}\` changes its line.`};let r=o(n);return{...r,note:`${m}${p(r.factCount)}`}}}),[h.TOOL_NAMES.memory_remember]:(0,d.tool)({description:"Write facts under a note that is on the listing.",inputSchema:e.object({path:r,facts:e.object({text:s,replaces:e.number().int().nullish().describe(`The id of the fact this replaces — from this note as handed back here or by \`${h.TOOL_NAMES.memory_recall}\`. Null if this is new. A fact that stopped being true is replaced rather than deleted, and so is a note saying the same thing twice: replacing keeps what changed on the record, deleting does not.`)}).array().min(1).describe("What to write under this note. Send everything that came up at once: one call is one pause in the conversation, three calls are three.")}),execute:async({path:c,facts:d})=>{let e=c.trim(),f=await (0,i.writeFacts)(e,d,a,b);if(!f)return{note:`${n(e)} A subject that is not on the listing gets a note of its own: \`${h.TOOL_NAMES.memory_create}\`, with its line.`};let g=o(f);return{...g,note:`${m}${p(g.factCount)}`}}}),[h.TOOL_NAMES.memory_describe]:(0,d.tool)({description:"Change the line a note is listed by, when it no longer says what the note is about.",inputSchema:e.object({path:r,description:e.string().describe("The new line, whole: what this note is about, with the names the user calls it by. Never a list of what is inside.")}),execute:async({path:a,description:b})=>{let c=a.trim(),d=b.trim();if((0,j.isAlwaysListed)(c))return{note:`${j.MEMORY_ALWAYS_LISTED.join(" and ")} keep their own line; it is not yours to change.`};let e=q(d);return e||(await (0,i.describeNote)(c,d)?{path:c,description:d,note:"Renamed. The listing in your instructions is from when this session opened and still shows the old line until the next one."}:{note:n(c)})}}),[h.TOOL_NAMES.memory_forget]:(0,d.tool)({description:"Delete facts for good.",inputSchema:e.object({factIds:e.number().int().array().min(1).describe("The ids that came with the facts when their notes were opened — every one to delete, in one call.")}),execute:async({factIds:a})=>{let b=[],c=[],d=new Set;for(let e of new Set(a)){let a=await (0,i.forgetFactById)(e);if(!a){b.push(e);continue}a.noteGone?(d.delete(a.path),c.push(a.path)):d.add(a.path)}if(!c.length&&!d.size)return{note:`No fact with id ${b.join(", ")}. Nothing was deleted.`};let e=["Deleted for good. The listing in your instructions is from when this session opened and still shows it that way until the next one.",1===c.length?`That was the last fact under ${c[0]}, so the note went with it.`:c.length?`That was the last of ${c.join(", ")}, so those notes went with them.`:"",b.length?`No fact with id ${b.join(", ")}, so those were skipped.`:""].filter(Boolean).join(" ");if(!d.size)return{note:e};let{notes:f}=await (0,i.readNotes)([...d],{touch:!1});return{notes:f.map(o),note:e}}})})]),c()}catch(a){c(a)}},!1),617594,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(762008),h=a.i(221214),i=a.i(780946),j=a.i(643020),k=a.i(706210),l=a.i(293480),m=a.i(182248),n=b([h,i]);[h,i]=n.then?(await n)():n;let q={description:`Routines: work that starts by itself, each one a bot, the work and a time — once at a moment, a time of day on chosen days, or every few hours. List them, make one, change one, or delete one. Every start opens a thread like one started by hand; its result reaches the conversation the same way. At most ${f.ROUTINE.max} exist.`,parameters:e.object({action:e.enum(["list","create","change","delete"]),routine:e.string().nullish().describe("With change or delete: the routine, by its name or ID."),bot:e.string().nullish().describe("With create: a name from the bot list. With change: a new bot."),label:e.string().nullish().describe("With create: two or three words naming it, in the user's language. It names every thread the routine opens, on screen and out loud."),request:e.string().nullish().describe("With create: the whole of the work, handed to the bot as written every time it starts. Nobody is there then to fill in what is missing, so everything it needs goes here, in the user's own language and words. Their request, never your reading of it."),at:e.string().nullish().describe('Starts once, at this moment, "YYYY-MM-DD HH:MM" in the user\'s own time, then switches itself off. Count "in an hour" or "tomorrow at eight" from **Now**. Give one of `at`, `time` or `everyHours`.'),time:e.string().nullish().describe('Starts at this time of day, 24-hour "HH:MM" in the user\'s own time, on `days`. Give one of `at`, `time` or `everyHours`.'),days:e.array(e.number().int().min(1).max(7)).nullish().describe("With `time`: the days it starts, 1 Monday to 7 Sunday. Omit for every day."),everyHours:e.number().int().nullish().describe(`Starts again this many hours after it last started, ${f.ROUTINE.minHours} at least. Give one of \`at\`, \`time\` or \`everyHours\`.`),enabled:e.boolean().nullish().describe("With change: false switches it off without deleting it, true back on.")})};function o(a){let b=a.runs[0];return{id:a.id,label:a.label,bot:a.bot,when:(0,j.scheduleText)(a.schedule),enabled:a.enabled,...a.enabled?{next:(0,k.whenOf)((0,k.toDate)(a.nextRunAt))}:{},request:(0,m.clip)(a.request,f.PROMPT_LINE.routineRequest),...b?{lastRun:{thread:b.id,status:b.status,at:(0,k.whenOf)((0,k.toDate)(b.updatedAt)),...b.outcome?{outcome:(0,m.clip)(b.outcome,f.PROMPT_LINE.routineOutcome)}:{}}}:{}}}let r=a=>{if((0,l.isPublicError)(a))return a.message;throw a};async function p(a){let b=(await (0,i.listRoutines)()).map(a=>`"${a.label}"`);return b.length?a?`There is no single routine called "${a}". The routines are: ${b.join(", ")}. Call again with one of those, or its ID.`:`Name the routine. The routines are: ${b.join(", ")}.`:"There are no routines yet."}a.s(["createRoutineTools",0,function(){return{[g.TOOL_NAMES.routine]:(0,d.tool)({description:q.description,inputSchema:q.parameters,execute:async a=>{if("list"===a.action)return{routines:(await (0,i.listRoutines)()).map(o)};let b=function(a){if([a.at,a.time,a.everyHours].filter(Boolean).length>1)return"Give one of `at`, `time` or `everyHours`, not two.";let b=a.at?{kind:"once",at:a.at}:a.time?{kind:"daily",time:a.time,days:a.days?.length?a.days:[1,2,3,4,5,6,7]}:a.everyHours?{kind:"every",hours:a.everyHours}:null;if(!b)return null;let c=j.RoutineScheduleSchema.safeParse(b);return c.success?c.data:c.error.issues[0].message}(a);if("string"==typeof b)return b;if("create"===a.action){if(!b)return"Say when it starts: `at`, `time` (with `days`), or `everyHours`.";let c=j.RoutineInputSchema.safeParse({bot:a.bot??"",label:a.label??"",request:a.request??"",schedule:b});if(!c.success)return`${c.error.issues[0].message}. Nothing was made — call again with bot, label, request and when.`;let d=(await (0,h.listJobBots)()).map(a=>a.name);if(!d.some(a=>a.toLowerCase()===c.data.bot.toLowerCase()))return`There is no bot called "${c.data.bot}". The bots are: ${d.join(", ")}. Nothing was made — call again with one of those.`;let e=await (0,i.createRoutine)(c.data).catch(r);if("string"==typeof e)return e;let f=(0,k.whenOf)((0,k.toDate)(e.nextRunAt));return{...o(e),note:"once"===e.schedule.kind?`${e.bot} starts "${e.label}" once, ${f}, and the routine then switches itself off. The start is a thread of its own, and its result reaches the conversation like any thread's.`:`${e.bot} starts "${e.label}" by itself, ${(0,j.scheduleText)(e.schedule)}, first ${f}. Each start is a thread of its own, and its result reaches the conversation like any thread's.`}}let c=a.routine?await (0,i.resolveRoutine)(a.routine):null;if(!c)return await p(a.routine);if("delete"===a.action)return await (0,i.deleteRoutine)(c.id),`"${c.label}" is deleted and starts no more. The threads it already opened stay.`;let d={...a.bot?{bot:a.bot}:{},...a.label?.trim()?{label:a.label.trim()}:{},...a.request?.trim()?{request:a.request.trim()}:{},...b?{schedule:b}:{},..."boolean"==typeof a.enabled?{enabled:a.enabled}:{}};if(!Object.keys(d).length)return"Nothing to change was given: bot, label, request, when, or enabled.";let e=await (0,i.updateRoutine)(c.id,d).catch(r);return"string"==typeof e?e:e?o(e):await p(a.routine)}})}}]),c()}catch(a){c(a)}},!1),622547,a=>a.a(async(b,c)=>{try{var d=a.i(47919),e=a.i(527990),f=a.i(723885),g=a.i(569572),h=a.i(762008),i=a.i(688034),j=a.i(725466),k=a.i(182248),l=b([j]);[j]=l.then?(await l)():l;let p=`Answer the question from the web. Lead with the answer, then
|
|
@@ -110,10 +112,10 @@ Every command is a new shell: \`cd\`, exported variables and an activated venv a
|
|
|
110
112
|
Nothing is watching it. A command that stops to ask never gets an answer and is killed after ${e.EXEC_TIMEOUT_MS/1e3}s, so pass the flag that skips the question (\`-y\`, \`--yes\`, \`--no-input\`), and send anything genuinely long to the background with its output redirected to a file.
|
|
111
113
|
|
|
112
114
|
Keys are not in the environment: every variable named like a key, a token or a secret is removed before the shell starts. An empty one is not an unset one — say which it was, and ask for what a command needs.`;a.s(["createWorkspaceTools",0,(a,e)=>{let k=!0===e.guide,l=async a=>{let b=e.bot;if(!b)return{result:await a(),memory:null};let c=await (0,g.holdBotMemory)(b);return{result:await a(),memory:await (0,g.keepBotMemory)(b,c)}},m=(0,c.tool)({description:i.BASH?"Run a bash command.":"Run a command in sh: this machine has no bash, so bash-only syntax fails.",inputSchema:d.default.object({command:d.default.string(),description:d.default.string().nullish().describe("One short line for the user: what this command does and why. Shown on their screen while it runs — not a restatement of the command.")}),execute:async({command:b},{abortSignal:c})=>{let{result:d,memory:f}=await l(()=>a.exec(b,{signal:c,env:e.env,timeoutMs:e.timeoutMs})),g=f?{...d,memory:f}:d;return k?(k=!1,{...g,guide:j}):g}});if(!e.write)return{[f.TOOL_NAMES.bash]:m};let n=(0,c.tool)({description:"Write a whole file — what was there is gone. Parent directories are created.",inputSchema:d.default.object({path:d.default.string().describe("Relative to the working directory — under one of its folders — or absolute"),content:d.default.string(),description:d.default.string().nullish().describe("One short line for the user: what this file is. Shown on their screen next to the path.")}),execute:async({path:c,content:d})=>{let f,g=a.resolve(c),i=(0,h.writeRefusal)(g,e.bot);if(i)return i;let{memory:j}=await l(()=>a.writeFile(c,d));return j??`Wrote ${(f=(0,b.relative)(a.cwd,g))&&!f.startsWith("..")?f:g} (${d.split("\n").length} lines)`}});return{[f.TOOL_NAMES.bash]:m,[f.TOOL_NAMES.write_file]:n}}])},346580,a=>{"use strict";a.s(["asWords",0,function(a,b,c=a=>a){let d=[];for(let e of a){if("tool"===e.role)continue;if("system"===e.role){d.push(e);continue}if("user"===e.role){d.push("string"==typeof e.content?{role:"user",content:c(e.content)}:e);continue}let a="string"==typeof e.content?[{type:"text",text:e.content}]:e.content,f=a.flatMap(a=>"text"===a.type?[a.text]:[]).join("\n").trim()||a.flatMap(a=>"tool-call"===a.type?[b(a.toolName,a.input)]:[]).join("\n");if(!f)continue;let g=d.at(-1);g?.role==="assistant"&&"string"==typeof g.content?d[d.length-1]={role:"assistant",content:`${g.content}
|
|
113
|
-
${c(f)}`}:d.push({role:"assistant",content:c(f)})}return d}])},641301,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(569572),e=a.i(821415);let f=a=>`${(0,e.botFolder)(a)}/memory`;async function g(a,b=d.BOT_MEMORY_LIMITS.files){let i=f(a),j=(0,c.join)(e.WORKSPACE,i),k=(await h(j)).sort((a,b)=>b.info.mtimeMs-a.info.mtimeMs),m=await Promise.all(k.slice(0,b).map(async({name:a,info:b})=>({file:a,path:`${i}/${a}`,line:await l((0,c.join)(j,a)),at:new Date(b.mtimeMs),bytes:b.size})));return{folder:i,entries:m,total:k.length}}async function h(a){let d=await (0,b.readdir)(a).catch(()=>[]);return(await Promise.all(d.filter(a=>!a.startsWith(".")).map(async d=>{let e=await (0,b.stat)((0,c.join)(a,d)).catch(()=>null);return e?.isFile()?{name:d,info:e}:null}))).filter(a=>null!==a)}async function i(a){let g=(0,c.join)(e.WORKSPACE,f(a)),i=new Map;return await Promise.all((await h(g)).map(async({name:a,info:e})=>{let f=e.size>4*d.BOT_MEMORY_LIMITS.chars?null:await (0,b.readFile)((0,c.join)(g,a),"utf8").catch(()=>null);i.set(a,{text:null!==f&&k(f)<=d.BOT_MEMORY_LIMITS.chars?f:null,size:e.size,mtimeMs:e.mtimeMs,atime:e.atime,mtime:e.mtime})})),i}async function j(a,g){let i=f(a),j=(0,c.join)(e.WORKSPACE,i),{files:l,chars:m}=d.BOT_MEMORY_LIMITS,n=[],o=[],p=0;for(let{name:a,info:d}of(await h(j))){p+=1;let e=g.get(a);if(e&&e.size===d.size&&e.mtimeMs===d.mtimeMs)continue;let f=(0,c.join)(j,a),h=k(await (0,b.readFile)(f,"utf8").catch(()=>""));if(h<=m){e||o.push(a);continue}let l=`${h.toLocaleString("en-US")} characters, past the ${m.toLocaleString("en-US")} a memory file holds`;e?null!==e.text?(await (0,b.writeFile)(f,e.text),await (0,b.utimes)(f,e.atime,e.mtime),n.push(`Not kept: \`${i}/${a}\` came to ${l}, so it is back as it was. Write it again shorter.`)):n.push(`\`${i}/${a}\` is ${l}. Shorten it.`):(await (0,b.rm)(f,{force:!0}),p-=1,n.push(`Not kept: \`${i}/${a}\` came to ${l}, so it was removed. Write it again shorter.`))}if(p>l&&o.length){await Promise.all(o.map(a=>(0,b.rm)((0,c.join)(j,a),{force:!0})));let a=o.map(a=>`\`${i}/${a}\``).join(", ");n.push(`Not kept: your memory holds ${l} files at most and this made ${p}, so ${a} ${1===o.length?"was":"were"} removed. Delete or merge files no longer worth keeping, then write it again.`)}return n.length?n.join("\n"):null}let k=a=>[...a.trim()].length;async function l(a){let c=await (0,b.open)(a,"r").catch(()=>null);if(!c)return"";try{let a=Buffer.alloc(1024),{bytesRead:b}=await c.read(a,0,1024,0),d=a.toString("utf8",0,b).split("\n").map(a=>a.trim()).filter(Boolean);if("---"===d[0]){let a=d.find(a=>a.startsWith("description:"));if(a)return a.slice(12).trim().replace(/^["']|["']$/g,"");let b=d.indexOf("---",1);return b>0?(d[b+1]??"").replace(/^#+\s*/,""):""}return(d[0]??"").replace(/^#+\s*/,"")}finally{await c.close()}}a.s(["botMemoryFolder",0,f,"holdBotMemory",0,i,"keepBotMemory",0,j,"listBotMemory",0,g])},654034,a=>a.a(async(b,c)=>{try{var d=a.i(
|
|
115
|
+
${c(f)}`}:d.push({role:"assistant",content:c(f)})}return d}])},641301,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(569572),e=a.i(821415);let f=a=>`${(0,e.botFolder)(a)}/memory`;async function g(a,b=d.BOT_MEMORY_LIMITS.files){let i=f(a),j=(0,c.join)(e.WORKSPACE,i),k=(await h(j)).sort((a,b)=>b.info.mtimeMs-a.info.mtimeMs),m=await Promise.all(k.slice(0,b).map(async({name:a,info:b})=>({file:a,path:`${i}/${a}`,line:await l((0,c.join)(j,a)),at:new Date(b.mtimeMs),bytes:b.size})));return{folder:i,entries:m,total:k.length}}async function h(a){let d=await (0,b.readdir)(a).catch(()=>[]);return(await Promise.all(d.filter(a=>!a.startsWith(".")).map(async d=>{let e=await (0,b.stat)((0,c.join)(a,d)).catch(()=>null);return e?.isFile()?{name:d,info:e}:null}))).filter(a=>null!==a)}async function i(a){let g=(0,c.join)(e.WORKSPACE,f(a)),i=new Map;return await Promise.all((await h(g)).map(async({name:a,info:e})=>{let f=e.size>4*d.BOT_MEMORY_LIMITS.chars?null:await (0,b.readFile)((0,c.join)(g,a),"utf8").catch(()=>null);i.set(a,{text:null!==f&&k(f)<=d.BOT_MEMORY_LIMITS.chars?f:null,size:e.size,mtimeMs:e.mtimeMs,atime:e.atime,mtime:e.mtime})})),i}async function j(a,g){let i=f(a),j=(0,c.join)(e.WORKSPACE,i),{files:l,chars:m}=d.BOT_MEMORY_LIMITS,n=[],o=[],p=0;for(let{name:a,info:d}of(await h(j))){p+=1;let e=g.get(a);if(e&&e.size===d.size&&e.mtimeMs===d.mtimeMs)continue;let f=(0,c.join)(j,a),h=k(await (0,b.readFile)(f,"utf8").catch(()=>""));if(h<=m){e||o.push(a);continue}let l=`${h.toLocaleString("en-US")} characters, past the ${m.toLocaleString("en-US")} a memory file holds`;e?null!==e.text?(await (0,b.writeFile)(f,e.text),await (0,b.utimes)(f,e.atime,e.mtime),n.push(`Not kept: \`${i}/${a}\` came to ${l}, so it is back as it was. Write it again shorter.`)):n.push(`\`${i}/${a}\` is ${l}. Shorten it.`):(await (0,b.rm)(f,{force:!0}),p-=1,n.push(`Not kept: \`${i}/${a}\` came to ${l}, so it was removed. Write it again shorter.`))}if(p>l&&o.length){await Promise.all(o.map(a=>(0,b.rm)((0,c.join)(j,a),{force:!0})));let a=o.map(a=>`\`${i}/${a}\``).join(", ");n.push(`Not kept: your memory holds ${l} files at most and this made ${p}, so ${a} ${1===o.length?"was":"were"} removed. Delete or merge files no longer worth keeping, then write it again.`)}return n.length?n.join("\n"):null}let k=a=>[...a.trim()].length;async function l(a){let c=await (0,b.open)(a,"r").catch(()=>null);if(!c)return"";try{let a=Buffer.alloc(1024),{bytesRead:b}=await c.read(a,0,1024,0),d=a.toString("utf8",0,b).split("\n").map(a=>a.trim()).filter(Boolean);if("---"===d[0]){let a=d.find(a=>a.startsWith("description:"));if(a)return a.slice(12).trim().replace(/^["']|["']$/g,"");let b=d.indexOf("---",1);return b>0?(d[b+1]??"").replace(/^#+\s*/,""):""}return(d[0]??"").replace(/^#+\s*/,"")}finally{await c.close()}}a.s(["botMemoryFolder",0,f,"holdBotMemory",0,i,"keepBotMemory",0,j,"listBotMemory",0,g])},654034,a=>a.a(async(b,c)=>{try{var d=a.i(666680),e=a.i(47919),f=a.i(527990),g=a.i(569572),h=a.i(738131),i=a.i(875931),j=a.i(735502),k=a.i(978876),l=a.i(762008),m=a.i(346580),n=a.i(446957),o=a.i(487591),p=a.i(821415),q=a.i(176668),r=a.i(987674),s=a.i(221214),t=a.i(109955),u=a.i(344853),v=b([h,i,j,k,s,u]);[h,i,j,k,s,u]=v.then?(await v)():v;let B=g.BOT_RUN.steps;async function w(a,b){var c;let d,m,v,w,z,E,F,G,H,I=b.parent??null,J=await (0,s.findJobBot)(a.bot.trim()),K=J?.name??a.bot.trim(),L=a=>b.emit({...a,bot:K,parent:I});if(!J)return void await L({type:"error",message:`No bot named "${a.bot}". Use a name from the list.`,retry:!1});let M=a.messages,N=await A(J),O=b.threadId?await (0,u.findThread)(b.threadId):null,[P,{own:Q,artifacts:R}]=await Promise.all([b.threadId?(0,p.openJobScratch)(b.threadId,O?.label??"job"):null,(0,p.openBotFolders)(K)]),S=b.session??(b.threadId?(0,p.botBrowserSession)(b.threadId,K):null),[T,U]=await Promise.all([(0,j.loadBotPrompt)(K,J.systemPrompt,{thread:b.threadId??null,owner:b.owner,caller:b.caller},{scratch:P,own:Q,artifacts:R}),(0,h.loadTools)({target:"bot",bot:K,thread:b.threadId??null,session:S,model:N})]),V=Math.min(await (0,i.compactBudget)(N.ref,J.compactAt),b.contextBudget||1/0),W=await (0,i.runEffort)(N.ref,J.effort),X=(0,i.promptCacheOptions)(N.ref,b.threadId?D(b.threadId,K):null),Y=!1,Z={...U,[l.TOOL_NAMES.send_message]:(0,f.tool)({description:k.sendMessageSpec.description,inputSchema:k.sendMessageSpec.parameters,execute:async(a,c)=>{let d=await b.send({...a,id:c.toolCallId});if("question"===a.kind&&(Y=!0),!d||"object"!=typeof d||!("to"in d))return d;let e=String(d.to);return e===t.ROOM_THURSDAY?d:{...d,note:`${e} has it now. When they finish, their answer — what they did and where the files are — comes to you as a new message and wakes you. Until then you do not know it: do not report it, guess it or do it yourself, and do not watch their folder. Go on with other work, or end your turn if there is none; the thread stays open.`}}})},$=new Set,_=(c=g.BOT_RUN.silenceMs,m=new AbortController,v=0,w=!1,z=()=>{clearTimeout(d),d=void 0,w||v>0||(d=setTimeout(()=>{m.abort(new DOMException(`The model sent nothing for ${Math.round(c/6e4)} minutes.`,"TimeoutError"))},c))},{signal:m.signal,touch:z,hold:()=>{v+=1,z()},release:()=>{v=Math.max(0,v-1),z()},end:()=>{w=!0,z()}});for(let[a,c]of Object.entries(Z)){let d=c.execute;d&&(c.execute=(c,e)=>{let f=(async()=>{b.signal?.throwIfAborted(),await L({type:"tool",id:e.toolCallId,name:a,input:c}),_.hold();try{b.signal?.throwIfAborted();let f=await d(c,e);if(f&&"object"==typeof f&&Symbol.asyncIterator in f){let a;for await(let b of f)a=b;f=a}return await L({type:"tool-result",id:e.toolCallId,name:a,output:f}),f}catch(b){throw await L({type:"tool-result",id:e.toolCallId,name:a,output:(0,i.modelErrorToString)(b),error:!0}),b}finally{_.release()}})();return $.add(f),f.finally(()=>$.delete(f)).catch(()=>{}),f})}let aa=Promise.resolve(),ab=()=>{},ac=0,ad=new e.ToolLoopAgent({model:N.model,instructions:T.text,tools:Z,reasoning:W,providerOptions:X,stopWhen:[(0,e.stepCountIs)(B),()=>Y],prepareStep:async({stepNumber:a,steps:c,messages:d})=>{await aa,b.signal?.throwIfAborted();let e={},f=(c.at(-1)?.usage.inputTokens??0)||d.reduce((a,b)=>a+(0,r.estimateTokens)("string"==typeof b.content?b.content:JSON.stringify(b.content))+4,0);ac=f;let g=d,h=b.compactNow?.()??!1;if((f>V||h)&&d.length>2){_.hold();let a=await y(N.model,Z,d,{signal:b.signal,budget:V,instructions:T.text,providerOptions:X}).finally(_.release);q.logger.debug(`compacted ${d.length} messages at ${f} tokens (budget ${V})`);let c=`${a.text}${await x(O?.id??null,d,P)}`;await L({type:"compact",text:c,usage:a.usage,messages:d.length,tokens:f}),g=[d[0],{role:"user",content:c}]}let i=a>0?await b.notes?.()??[]:[];return(i.length&&(g=[...g,...i.map(a=>({role:"user",content:a}))]),g===d)?e:{...e,messages:g}}}),ae=(E=[],F=[],G=!1,{push(a){let b=F.shift();b?b(a):E.push(a)},take(){let a=E.shift();return a?Promise.resolve(a):G?Promise.resolve(null):new Promise(a=>F.push(a))},end(){for(let a of(G=!0,F.splice(0)))a(null)}}),af=b.signal?AbortSignal.any([b.signal,_.signal]):_.signal;_.touch();let ag=new AbortController,ah=AbortSignal.any([af,ag.signal]);try{H=await ad.stream({messages:M,abortSignal:ah,onStepEnd:a=>{aa=new Promise(a=>{ab=a}),ae.push({messages:function(a){if(!a.toolResults.length)return a.response.messages;let b=new Map(a.toolResults.map(a=>[a.toolCallId,a.output]));return a.response.messages.map(a=>"tool"!==a.role?a:{...a,content:a.content.map(a=>{if("tool-result"!==a.type||!b.has(a.toolCallId))return a;let c=b.get(a.toolCallId);return{...a,output:"string"==typeof c?{type:"text",value:c}:{type:"json",value:c}}})})}(a),usage:C(a.usage)})}})}catch(a){throw _.end(),ag.abort(),await Promise.allSettled([...$]),a}let ai="",aj="",ak=null,al=a=>{q.logger.error(`${K}: the model run broke`,a);let b=(0,i.modelErrorToString)(a),c=!(0,i.isProviderRefusal)(a);if(!(0,i.isContextOverflow)(a))return{type:"error",message:b,retry:c};let d=Math.floor(Math.min(V,ac||V)*g.BOT_RUN.overflowShrink);return{type:"error",message:b,budget:Math.max(n.COMPACT_AT_MIN,d),retry:c}};af.addEventListener("abort",()=>{ae.end(),ab()},{once:!0});try{for await(let a of H.stream)switch(_.touch(),a.type){case"start-step":aj="",ai="";break;case"text-delta":ai+=a.text;break;case"text-end":{let a=ai.trim();if(ai="",!a)break;aj=[aj,a].filter(Boolean).join("\n\n"),await L({type:"text",text:a});break}case"tool-call":await L({type:"tool",id:a.toolCallId,name:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:a.providerMetadata});break;case"tool-result":await L({type:"tool-result",id:a.toolCallId,name:a.toolName,output:a.output});break;case"tool-error":await L({type:"tool-result",id:a.toolCallId,name:a.toolName,output:(0,i.modelErrorToString)(a.error),error:!0});break;case"finish-step":{ak=a.finishReason;let b=await ae.take();b&&await L({type:"step",...b,budget:V}),ab();break}case"abort":if(b.signal?.aborted)return;await L(al(a.reason??"The model stopped sending."));return;case"error":await L(al(a.error));return}}finally{ag.abort(),ae.end(),_.end(),ab(),await Promise.allSettled([...$]),S&&(0,o.renewSignIns)(S).catch(a=>q.logger.warn(`${K}: kept sign-ins were not renewed`,a))}try{await H.finalStep}catch(a){if(b.signal?.aborted)return;await L(al(a));return}"content-filter"===ak?await L({type:"error",message:"The provider's content filter stopped the response.",retry:!1}):await L({type:"turn-end",text:aj,stopped:!Y&&("length"===ak||"error"===ak||"tool-calls"===ak)})}async function x(a,b,c){try{let d=a?await (0,u.listWrittenPaths)(a):(0,u.writtenPathsIn)(b.map(a=>a.content)),e=await (0,p.filesOnDisk)(d,c);if(!e.length)return"";let f=e.slice(-g.BOT_RUN.compactFiles),h=e.length-f.length,i=f.map(a=>`- ${a}`);return h&&i.unshift(`- …and ${h} older ones`),`
|
|
114
116
|
|
|
115
117
|
Files this job has on disk now — open one rather than fetching again what is in it:
|
|
116
|
-
${i.join("\n")}`}catch(a){return
|
|
118
|
+
${i.join("\n")}`}catch(a){return q.logger.warn("files under the summary could not be listed",a),""}}async function y(a,b,c,d){let e;try{return await z(a,b,c,d)}catch(a){if(d.signal?.aborted)throw a;e=a}if((0,i.isContextOverflow)(e)){let f=(0,m.asWords)(c,(a,b)=>`${a}: ${(0,u.argumentLine)(a,b)}`);try{return await z(a,b,f,d)}catch(a){if(d.signal?.aborted)throw a;e=a}}throw Error(`Could not compact the context (${(0,i.modelErrorToString)(e)}).`,{cause:e})}async function z(a,b,c,d){let f,{text:h,usage:i}=await (0,e.generateText)({model:a,instructions:d.instructions,tools:b,toolChoice:"none",messages:[...c,{role:"user",content:(f=(a=>{let{min:b,max:c,perTokens:d}=g.BOT_RUN.summaryWords;return Math.min(c,Math.max(b,Math.round(a/d)))})(d.budget),`Compact your context. The first message above — who handed you the job, and the job — stays exactly as it is. Everything after it is replaced by what you write now, and you carry on from that first message and this alone; nothing else above can be read again. Write it for a fresh copy of you that has your tools, your instructions and that first message, but has seen none of the rest.
|
|
117
119
|
|
|
118
120
|
Cover all of it, and prefer a fact over a description of a fact:
|
|
119
121
|
|
|
@@ -124,9 +126,10 @@ Cover all of it, and prefer a fact over a description of a fact:
|
|
|
124
126
|
- **What did not work**, and why: the url that 404s, the endpoint that needs POST not GET, the selector that is not there, the site that refuses a headless browser, the argument a tool rejected. This is the part that stops the next steps repeating an hour of yours.
|
|
125
127
|
- **What is left**, in the order you would do it.
|
|
126
128
|
|
|
127
|
-
Plain text, under ${
|
|
129
|
+
Plain text, under ${f} words. No preamble, no headings about the summary itself, no account of how you have been going.`)}],abortSignal:d.signal,timeout:g.BOT_RUN.silenceMs,providerOptions:d.providerOptions}),j=h.trim();if(!j)throw Error("The summary of the context came back empty, so there is nothing to carry on from.");return{text:`Everything between the first message and here was compacted. Below is your own summary of it; carry on from the first message and this.
|
|
128
130
|
|
|
129
|
-
${j}`,usage:
|
|
131
|
+
${j}`,usage:C(i)}}let C=a=>({input:a.inputTokens??0,output:a.outputTokens??0,cacheRead:a.inputTokenDetails?.cacheReadTokens??0,cacheWrite:a.inputTokenDetails?.cacheWriteTokens??0}),D=(a,b)=>(0,d.createHash)("sha256").update(`${a}
|
|
132
|
+
${b}`).digest("hex").slice(0,32);function A(a,b={}){return a.provider&&a.model?(0,i.getTextModel)({provider:a.provider,model:a.model}):(0,i.resolveDefaultModel)(void 0,b).then(i.getTextModel)}a.s(["resolveModel",0,A,"resumeTranscript",0,function(a,b=new Map){let c=new Map,d=new Set;for(let b of a)if(("tool"===b.role||"assistant"===b.role)&&Array.isArray(b.content))for(let a of b.content)"tool-result"===a.type&&(c.has(a.toolCallId)||c.set(a.toolCallId,a),"assistant"===b.role&&d.add(a.toolCallId));let e=[],f=new Set;for(let g of a){if("tool"===g.role){let a=g.content.filter(a=>"tool-result"!==a.type);a.length&&e.push({...g,content:a});continue}if("assistant"!==g.role||"string"==typeof g.content){e.push(g);continue}let a=[],h=[];for(let e of g.content){if("tool-call"!==e.type){h.push(e);continue}if(f.has(e.toolCallId))continue;let g=e.input;if("string"==typeof g)try{g=JSON.parse(g)}catch{g=void 0}if(!e.toolCallId||void 0===g){h.push({type:"text",text:"A tool argument stream was interrupted before a complete call was recorded. Inspect the saved work before continuing."});continue}let i=e.toolName===l.TOOL_NAMES.send_message?b.get(e.toolCallId):void 0,j=c.get(e.toolCallId)??(i?{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"json",value:i}}:void 0);if(e.providerExecuted&&(!j||!d.has(e.toolCallId))){h.push({type:"text",text:j?`The provider operation ${e.toolName} returned this data before its native continuation was interrupted: ${JSON.stringify(j.output)}`:`The provider operation ${e.toolName} was interrupted without a recorded result. Its remote execution state is unknown.`});continue}f.add(e.toolCallId),h.push({...e,input:g}),d.has(e.toolCallId)||a.push(j??{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:"No result: execution was interrupted before a result was recorded. The outcome is unknown. Inspect the current state before repeating the action."}})}h.length&&e.push({...g,content:h}),a.length&&e.push({role:"tool",content:a})}return e},"runBot",0,w]),c()}catch(a){c(a)}},!1),674986,a=>a.a(async(b,c)=>{try{var d=a.i(136340),e=a.i(203469),f=a.i(569572),g=a.i(875931),h=a.i(735502),i=a.i(569549),j=a.i(684321),k=a.i(821415),l=a.i(956802),m=a.i(176668),n=a.i(293480),o=a.i(8412),p=a.i(182248),q=a.i(221214),r=a.i(654034),s=a.i(446957),t=a.i(839430),u=a.i(109955),v=a.i(344853),w=b([g,h,i,q,r,t,v]);[g,h,i,q,r,t,v]=w.then?(await w)():w;let K=globalThis.__roomRuns??=new Map,L=globalThis.__roomThreadLock??=(0,o.createKeyedLock)(),M=globalThis.__roomCompactAsked??=new Set,N=(a,b)=>`${a}
|
|
130
133
|
${b}`;async function x(a){let b=await (0,q.findJobBot)(a.bot);(!b||b.disabled)&&(0,n.publicError)("Choose an enabled bot.");let{from:c,routine:d,...e}={...a,bot:b.name},f=(0,h.buildThreadOpening)({bot:e.bot,request:e.request,from:c,routine:d}),g=await (0,v.insertThread)({...e,routineId:d?.id??null,opening:f});return await z(g.id),g.id}async function y(a,b,c="user",d,e){let f=null;return await L(a,async()=>{let g=await (0,v.findThread)(a);if(g||(0,n.publicError)("No such thread."),d){let b=(await (0,t.listRoomWork)(a)).find(a=>a.bot.toLowerCase()===d.trim().toLowerCase());b&&b.bot!==u.ROOM_THURSDAY||(0,n.publicError)("Choose a participant in this thread."),d=b.bot}b.trim()===s.THREAD_CONTINUE&&(0,s.isAppStop)(g.pending)?(await (0,t.resumeRoom)(a),(await (0,t.listRoomWork)(a)).some(a=>"queued"===a.state)||(f=await (0,t.tellRoom)(a,"Continue from the saved conversation.","user"===c?u.ROOM_USER:u.ROOM_THURSDAY,d,void 0,!1))):f=await (0,t.tellRoom)(a,b,"user"===c?u.ROOM_USER:u.ROOM_THURSDAY,d,e)}),await z(a),f}async function z(a){await L(a,async()=>{for(let b=0;b<2;b++){let b;for(;b=await (0,t.claimRoomWork)(a);)!function(a){let b,c=new AbortController,d=new Promise(a=>{b=a});K.set(a.id,{threadId:a.threadId,stop:c,done:d}),A(a,c.signal).catch(b=>m.logger.error(`thread ${a.threadId}: participant`,b)).finally(()=>{K.delete(a.id),b(),z(a.threadId).catch(b=>m.logger.error(`thread ${a.threadId}: scheduling`,b))})}(b);await (0,t.settleRoom)(a)}})}async function A(a,b){let c=await B(a,b);if(c?.failure?.retry&&!b.aborted&&(await (0,t.noteRoomBreak)(a,c.failure.message),await (0,d.setTimeout)(f.BOT_RUN.retryMs,void 0,{signal:b}).catch(()=>{}),b.aborted||(c=await B(a,b))),!c||b.aborted)return;let g=c.failure?.message,h=c.ending;if(g||!h||h.stopped){let b=g??"The turn was interrupted. Continue from the saved conversation.";L(a.threadId,async()=>{let c=(await (0,t.listRoomWork)(a.threadId)).find(b=>b.id===a.id);if(c?.state!=="running"||c.generation!==a.generation)return;let d=C(a.threadId);await (0,t.pauseRoom)(a.threadId,b),await d}).catch(b=>m.logger.error(`thread ${a.threadId}: pausing`,b));return}await (0,t.finishRoomWork)(a,h.text);let n=await (0,v.findThread)(a.threadId);if(n?.status==="done"){let a=(0,p.plainText)(n.outcome??"").slice(0,f.FINISHED_NOTICE.words);e.presence.watching||await (0,i.isAnyCallLive)()||(0,l.desktopNotify)(n.label,a);let b=await (0,k.filesOnDisk)((0,j.pathsIn)(n.outcome??""),null);e.appEvents.emit({type:"finished",threadId:n.id,label:n.label,bot:n.bot,words:a,paths:(0,j.leadFirst)(b)})}}async function B(a,b){let c=new O(a,b),d=null,e=null;try{let f=await (0,v.findThread)(a.threadId);if(!f)return null;(await (0,t.listParticipantTranscript)(a.threadId,a.bot)).length||await (0,t.appendRoomMessage)(a.threadId,{bot:a.bot,parent:a.id,role:"user",content:`Request: ${f.request}
|
|
131
134
|
Coordinator: ${f.bot}. Continue as ${a.bot} in this thread.`,hidden:!0}),await (0,t.consumeRoomInbox)(a);let g=await (0,t.listParticipantTranscript)(a.threadId,a.bot);await (0,r.runBot)({bot:a.bot,messages:(0,r.resumeTranscript)(g,await (0,t.listRoomReceipts)(a.threadId,a.bot,g))},{signal:b,threadId:a.threadId,parent:a.id,caller:a.caller,owner:f.bot,contextBudget:await (0,t.roomContextBudget)(a.threadId,a.bot),compactNow:()=>M.delete(N(a.threadId,a.bot)),session:(0,k.botBrowserSession)(a.threadId,a.bot),notes:()=>(0,t.consumeRoomInbox)(a),send:async c=>{b.throwIfAborted();let d=c.to.trim();if(d.toLowerCase()===u.ROOM_THURSDAY.toLowerCase())d=u.ROOM_THURSDAY;else{let a=await (0,q.findJobBot)(d);(!a||a.disabled)&&(0,n.publicError)(`No enabled bot named "${d}".`),d=a.name}let e=await (0,t.sendRoomMessage)(a,{...c,to:d});return z(a.threadId).catch(a=>m.logger.error("room message scheduling",a)),e},emit:async g=>{(!b.aborted||"tool-result"===g.type)&&(await c.on(g),"step"===g.type&&await (0,v.addThreadUsage)(a.threadId,g.usage,a.bot===f.bot?{tokens:g.usage.input,budget:g.budget}:null),"compact"===g.type&&await (0,v.addThreadUsage)(a.threadId,g.usage),"turn-end"===g.type&&(d=g),"error"===g.type&&(e={message:g.message,retry:g.retry},g.budget&&await (0,t.lowerRoomContextBudget)(a,g.budget)))}})}catch(c){b.aborted||(m.logger.error(`thread ${a.threadId}: ${a.bot} broke`,c),e={message:(0,g.modelErrorToString)(c),retry:!(0,n.isPublicError)(c)&&!(0,g.isProviderRefusal)(c)})}return{ending:d,failure:e}}class O{work;signal;lane;assistant;tool;parts;calls;results;constructor(a,b){this.work=a,this.signal=b,this.lane=(0,p.PromiseChain)(),this.assistant=null,this.tool=null,this.parts={assistant:[],tool:[]},this.calls=new Set,this.results=new Set}async write(a,b,c=!1){let d={bot:this.work.bot,parent:this.work.id,role:b.role,content:b.content,compact:c,note:c};return null===a?(0,t.appendRoomMessage)(this.work.threadId,d):(await (0,v.upsertMessage)(this.work.threadId,a,d),a)}on(a){return this.lane(async()=>{if(!this.signal.aborted||"tool-result"===a.type)if("text"===a.type)this.parts.assistant.push({type:"text",text:a.text}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant});else if("tool"===a.type){if(this.calls.has(a.id)){let b=this.parts.assistant.find(b=>"tool-call"===b.type&&b.toolCallId===a.id);b&&"tool-call"===b.type&&a.providerOptions&&(b.providerOptions=a.providerOptions,this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant}));return}this.calls.add(a.id),this.parts.assistant.push({type:"tool-call",toolCallId:a.id,toolName:a.name,input:a.input,...a.providerExecuted?{providerExecuted:!0}:{},...a.providerOptions?{providerOptions:a.providerOptions}:{}}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant})}else if("tool-result"===a.type){if(this.results.has(a.id))return;this.results.add(a.id),this.parts.tool.push({type:"tool-result",toolCallId:a.id,toolName:a.name,output:a.error?{type:"error-text",value:String(a.output)}:"string"==typeof a.output?{type:"text",value:a.output}:{type:"json",value:a.output}}),this.tool=await this.write(this.tool,{role:"tool",content:this.parts.tool})}else if("step"===a.type){let b=[this.assistant,this.tool];for(let[c,d]of a.messages.entries())await this.write(b[c]??null,d);let c=b.slice(a.messages.length).filter(a=>null!==a);c.length&&await (0,v.deleteMessages)(this.work.threadId,c),this.assistant=this.tool=null,this.parts={assistant:[],tool:[]}}else"compact"===a.type&&await this.write(null,{role:"user",content:a.text},!0)})}}async function C(a){let b=[...K.values()].filter(b=>b.threadId===a);for(let a of b)a.stop.abort();await Promise.all(b.map(a=>a.done))}async function D(a){await L(a,async()=>{let b=await (0,v.findThread)(a);b||(0,n.publicError)("No such thread."),b.endedAt&&(0,n.publicError)("That thread has already ended."),await (0,t.cancelRoom)(a),await (0,v.updateThread)(a,{status:"cancelled",outcome:null,pending:null,seen:!0,endedAt:new Date}),await C(a),await (0,k.closeJobShell)(a)})}async function E(a){return L(a,()=>F(a))}async function F(a){let b=await (0,v.findThread)(a);await (0,t.cancelRoom)(a),await C(a),await (0,k.removeJobBrowsers)(a);let c=await (0,v.deleteThread)(a);return c&&b&&await (0,k.removeJobScratch)(a,b.label),c}async function G(a){let b=a?.getTime(),c=a=>void 0===b||(a.endedAt??a.updatedAt).getTime()<b,d=0;for(let a of(await (0,v.listThreadFolders)()))("done"===a.status||"cancelled"===a.status)&&c(a)&&await L(a.id,async()=>{let b=await (0,v.findThread)(a.id);b?.status!=="done"&&b?.status!=="cancelled"||c(b)&&await F(a.id)&&(d+=1)});return d}async function H(){let a=Date.now()-f.WORKSPACE_KEEP.forMs,b=b=>("done"===b.status||"cancelled"===b.status)&&(b.endedAt??b.updatedAt).getTime()<a,c=new Set(await (0,k.listScratchFolders)()),d=[];for(let a of(await (0,v.listThreadFolders)())){let e=(0,k.jobScratch)(a.id,a.label);c.delete(e)&&b(a)&&await L(a.id,async()=>{let c=await (0,v.findThread)(a.id);c&&b(c)&&(await (0,k.closeHiddenBrowser)(a.id),await (0,k.removeJobScratch)(a.id,a.label),d.push(e))})}return d.push(...await (0,k.removeUnchangedFolders)([...c])),await (0,k.pruneJobFiles)(),d.length&&m.logger.info(`cleared ${d.length} old job folder(s): ${d.join(", ")}`),d}async function I(){for(let a of(await (0,v.listRunningThreadIds)()))await L(a,async()=>{[...K.values()].some(b=>b.threadId===a)||(await (0,v.findThread)(a))?.status==="running"&&await (0,t.pauseRoom)(a,"The server restarted. Resume from the saved conversation.")})}async function J(a){let b=await (0,v.listRunningThreadIds)();await Promise.all(b.map(b=>L(b,async()=>{(await (0,v.findThread)(b))?.status==="running"&&(await C(b),await (0,t.pauseRoom)(b,a))})))}a.s(["answerThread",0,y,"askCompact",0,function(a,b){M.add(N(a,b))},"cancelThread",0,D,"pauseThreads",0,J,"removeFinishedThreads",0,G,"removeThread",0,E,"startThread",0,x,"sweepJobFiles",0,H,"sweepThreads",0,I]),c()}catch(a){c(a)}},!1),317844,a=>a.a(async(b,c)=>{try{var d,e=a.i(106450),f=a.i(64203),g=a.i(569572),h=a.i(176668),i=a.i(182248),j=a.i(947950),k=a.i(899284),l=b([j]);[j]=l.then?(await l)():l;class m extends Error{serverName;authorizationUrl;constructor(a,b){super(`MCP server "${a}" requires authorization`),this.serverName=a,this.authorizationUrl=b,this.name="McpAuthRequiredError"}}class n{store;serverName;oauth;callbackUrl;clientName;lastAuthorizationUrl;constructor(a,b,c,d,e){this.store=a,this.serverName=b,this.oauth=c,this.callbackUrl=d,this.clientName=e}get redirectUrl(){return this.callbackUrl}get clientMetadata(){return{client_name:this.clientName,redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post"}}async persist(a){this.oauth={...this.oauth,...a},await this.store.saveOAuth(this.serverName,this.oauth)}clientInformation(){return this.oauth.clientInformation}async saveClientInformation(a){await this.persist({clientInformation:a})}tokens(){return this.oauth.tokens}async saveTokens(a){await this.persist({tokens:a})}authorizationServerInformation(){return this.oauth.authorizationServer}async saveAuthorizationServerInformation(a){await this.persist({authorizationServer:a})}codeVerifier(){if(!this.oauth.codeVerifier)throw Error("No code verifier saved");return this.oauth.codeVerifier}async saveCodeVerifier(a){await this.persist({codeVerifier:a})}state(){return crypto.randomUUID()}async saveState(a){await this.persist({state:a})}storedState(){return this.oauth.state}redirectToAuthorization(a){this.lastAuthorizationUrl=a}async invalidateCredentials(a){let b={...this.oauth};("all"===a||"client"===a)&&(b.clientInformation=void 0),("all"===a||"tokens"===a)&&(b.tokens=void 0),("all"===a||"verifier"===a)&&(b.codeVerifier=void 0),this.oauth=b,await this.store.saveOAuth(this.serverName,b)}}let o=globalThis;o.__thursdayMcpManager&&o.__thursdayMcpManager.dispose(),d={callbackUrl:new URL("/api/mcp/oauth/callback",g.APP_URL).href,clientName:g.APP_NAME},o.__thursdayMcpManager=new class a{store;sessions;connecting;callbackUrl;clientName;constructor(a,b){this.store=a,this.sessions=new Map,this.connecting=new Map,this.callbackUrl=b.callbackUrl,this.clientName=b.clientName??g.APP_NAME}async connect(a){let b=this.connecting.get(a);if(b)return b;let c=this.doConnect(a).finally(()=>this.connecting.delete(a));return this.connecting.set(a,c),c}async callTool(a,b,c,d){let f=await this.ensureClient(a);try{let e=await f.callTool({name:b,arguments:c,options:d?{signal:d}:void 0});return this.touch(a),e}catch(b){if(b instanceof e.UnauthorizedError)throw await this.closeSession(a),new m(a);throw b}}async finishAuthorization(a){let b=a.get("state"),c=a.get("code");if(!b||!c)throw Error("OAuth callback is missing code or state");let d=await this.store.findByOAuthState(b);if(!d||!(0,k.isRemoteConfig)(d.config))throw Error("No server is waiting for this authorization");let f=this.providerFor(d),g=await (0,e.auth)(f,{serverUrl:d.config.url,authorizationCode:c,callbackState:b});if("AUTHORIZED"!==g)throw Error(`Token exchange ended in "${g}"`);return await f.invalidateCredentials("verifier"),await this.connect(d.name),d.name}async disconnect(a){await this.closeSession(a)}async dispose(){await Promise.all([...this.sessions.keys()].map(a=>this.closeSession(a)))}async doConnect(a){await this.closeSession(a);let b=await this.store.load(a);if(!b)throw Error(`Unknown MCP server "${a}"`);let c={};try{let d=await this.openClient(b,c),e=(await d.listTools()).tools.map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,outputSchema:a.outputSchema}));return this.adopt(a,d),await this.store.saveConnectionResult(a,{toolInfo:e,lastError:null}),h.logger.info(`mcp "${a}" connected — ${e.length} tools`),{status:"connected",tools:e}}catch(l){var d,f;let g;if(l instanceof e.UnauthorizedError||l?.cause instanceof e.UnauthorizedError){let b=c.href;if(b)return await this.store.saveConnectionResult(a,{toolInfo:[],lastError:"Authorization required — finish sign-in in the opened tab"}),{status:"auth_required",authorizationUrl:b}}let j=(d=l,f=b,g=(0,i.errorToString)(d),(0,k.isRemoteConfig)(f.config)&&!f.oauth?.clientInformation&&/Invalid OAuth error response/.test(g)?`This server does not let an app register itself for sign-in, so it cannot be connected here. It answered: ${g}`:g);throw await this.store.saveConnectionResult(a,{toolInfo:[],lastError:j}),h.logger.warn(`mcp "${a}" failed — ${j}`),Error(j,{cause:l})}}async openClient(a,b={}){if((0,k.isRemoteConfig)(a.config)){let c=this.providerFor(a);try{return await (0,e.createMCPClient)({name:this.clientName,transport:{type:"http",url:a.config.url,headers:a.config.headers,authProvider:c,redirect:"follow"}})}finally{b.href=c.lastAuthorizationUrl?.href}}return(0,e.createMCPClient)({name:this.clientName,transport:new f.Experimental_StdioMCPTransport({command:a.config.command,args:a.config.args,env:a.config.env})})}providerFor(a){return new n(this.store,a.name,a.oauth??{},this.callbackUrl,this.clientName)}async ensureClient(a){let b=this.sessions.get(a);if(b)return b.client;let c=await this.connect(a);if("auth_required"===c.status)throw new m(a,c.authorizationUrl);let d=this.sessions.get(a);if(!d)throw Error(`Session for "${a}" vanished mid-connect`);return d.client}adopt(a,b){this.sessions.set(a,{client:b,idleTimer:this.armIdleTimer(a)})}touch(a){let b=this.sessions.get(a);b&&(clearTimeout(b.idleTimer),b.idleTimer=this.armIdleTimer(a))}armIdleTimer(a){let b=setTimeout(()=>{this.closeSession(a)},g.MCP_IDLE_MS);return b.unref?.(),b}async closeSession(a){let b=this.sessions.get(a);b&&(this.sessions.delete(a),clearTimeout(b.idleTimer),await b.client.close().catch(()=>{}))}}({load:a=>(0,j.findServer)(a),saveOAuth:(a,b)=>(0,j.saveOAuthData)(a,b),saveConnectionResult:(a,b)=>null===b.lastError?(0,j.syncServerTools)(a,b.toolInfo):(0,j.saveConnectionError)(a,b.lastError),findByOAuthState:a=>(0,j.findServerByOAuthState)(a)},d);let p=o.__thursdayMcpManager;a.s(["McpAuthRequiredError",0,m,"mcpManager",0,p]),c()}catch(a){c(a)}},!1),947950,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(351674),f=a.i(203469),g=a.i(184838),h=a.i(714428),i=a.i(899284),j=b([g]);async function k(a){var b;let[c]=await g.database.select({name:h.mcpServerTable.name,config:h.mcpServerTable.config,lastError:h.mcpServerTable.lastError,toolsSyncedAt:h.mcpServerTable.toolsSyncedAt}).from(h.mcpServerTable).where((0,d.eq)(h.mcpServerTable.name,a));return c?{...c,config:(b=c.config,(0,i.isRemoteConfig)(b)?{url:b.url}:{command:b.command,args:b.args}),tools:await l(a)}:null}async function l(a){return g.database.select({id:h.mcpToolTable.id,name:h.mcpToolTable.name,description:h.mcpToolTable.description,inputSchema:h.mcpToolTable.inputSchema,outputSchema:h.mcpToolTable.outputSchema}).from(h.mcpToolTable).where((0,d.eq)(h.mcpToolTable.serverName,a)).orderBy(h.mcpToolTable.name)}async function m(a){let[b]=await g.database.select().from(h.mcpServerTable).where((0,d.eq)(h.mcpServerTable.name,a));return b??null}[g]=j.then?(await j)():j;let u=()=>f.appEvents.emit({type:"mcp"});async function n(a){let[b]=await g.database.insert(h.mcpServerTable).values({...a,lastError:null}).onConflictDoUpdate({target:h.mcpServerTable.name,set:{config:a.config,lastError:null}}).returning();return u(),b}async function o(a,b){await g.database.transaction(async c=>{b.length&&await c.insert(h.mcpToolTable).values(b.map(b=>({...b,serverName:a}))).onConflictDoUpdate({target:[h.mcpToolTable.serverName,h.mcpToolTable.name],set:{description:p(h.mcpToolTable.description),inputSchema:p(h.mcpToolTable.inputSchema),outputSchema:p(h.mcpToolTable.outputSchema)}}),await c.delete(h.mcpToolTable).where(b.length?(0,d.and)((0,d.eq)(h.mcpToolTable.serverName,a),(0,d.notInArray)(h.mcpToolTable.name,b.map(a=>a.name))):(0,d.eq)(h.mcpToolTable.serverName,a)),await c.update(h.mcpServerTable).set({lastError:null,toolsSyncedAt:new Date}).where((0,d.eq)(h.mcpServerTable.name,a))}),u()}function p(a){return e.sql.raw(`excluded."${a.name}"`)}async function q(a,b){await g.database.update(h.mcpServerTable).set({lastError:b}).where((0,d.eq)(h.mcpServerTable.name,a)),u()}async function r(a,b){await g.database.update(h.mcpServerTable).set({oauth:b}).where((0,d.eq)(h.mcpServerTable.name,a)),u()}async function s(a){let[b]=await g.database.select().from(h.mcpServerTable).where(e.sql`json_extract(${h.mcpServerTable.oauth}, '$.state') = ${a}`);return b??null}async function t(a){let b=await g.database.delete(h.mcpServerTable).where((0,d.eq)(h.mcpServerTable.name,a)).returning();return b.length>0&&u(),b.length>0}a.s(["deleteServer",0,t,"findPinnedTools",0,function(a){return g.database.select({server:h.mcpToolTable.serverName,name:h.mcpToolTable.name,description:h.mcpToolTable.description,inputSchema:h.mcpToolTable.inputSchema}).from(h.botMcpToolTable).innerJoin(h.mcpToolTable,(0,d.eq)(h.botMcpToolTable.toolId,h.mcpToolTable.id)).where((0,d.eq)(h.botMcpToolTable.botName,a)).orderBy(h.mcpToolTable.serverName,h.mcpToolTable.name)},"findServer",0,m,"findServerByOAuthState",0,s,"findServerDetail",0,k,"findToolSchemas",0,function(a,b){return b.length?g.database.select({name:h.mcpToolTable.name,description:h.mcpToolTable.description,inputSchema:h.mcpToolTable.inputSchema}).from(h.mcpToolTable).where((0,d.and)((0,d.eq)(h.mcpToolTable.serverName,a),(0,d.inArray)(h.mcpToolTable.name,b))).orderBy(h.mcpToolTable.name):Promise.resolve([])},"listServerNames",0,function(){return g.database.select({name:h.mcpServerTable.name}).from(h.mcpServerTable).orderBy(h.mcpServerTable.name)},"listToolNames",0,function(a){let b=g.database.select({server:h.mcpToolTable.serverName,name:h.mcpToolTable.name}).from(h.mcpToolTable);return a?b.where((0,d.eq)(h.mcpToolTable.serverName,a)).orderBy(h.mcpToolTable.name):b.orderBy(h.mcpToolTable.serverName,h.mcpToolTable.name)},"saveConnectionError",0,q,"saveOAuthData",0,r,"syncServerTools",0,o,"upsertServer",0,n]),c()}catch(a){c(a)}},!1),899284,a=>{"use strict";var b=a.i(53112),c=a.i(706210);let d=b.z.object({url:b.z.url(),headers:b.z.record(b.z.string(),b.z.string()).optional()}),e=b.z.object({command:b.z.string().min(1),args:b.z.array(b.z.string()).optional(),env:b.z.record(b.z.string(),b.z.string()).optional()}),f=b.z.union([d,e]),g=b.z.object({name:b.z.string(),description:b.z.string().optional(),inputSchema:b.z.looseObject({}).optional(),outputSchema:b.z.looseObject({}).optional()});b.z.object({clientInformation:b.z.looseObject({}).optional(),tokens:b.z.looseObject({}).optional(),authorizationServer:b.z.looseObject({}).optional(),codeVerifier:b.z.string().optional(),state:b.z.string().optional()});let h=b.z.object({name:b.z.string().min(1).max(40),config:f,toolCount:b.z.number().int(),lastError:b.z.string().nullish()}),i=g.extend({id:b.z.number().int(),description:b.z.string().nullish()});h.omit({toolCount:!0}).extend({tools:i.array().default([]),toolsSyncedAt:c.DateLikeSchema});let j=b.z.object({name:b.z.string().min(1,"Name is required").max(40).regex(/^[a-zA-Z0-9_-]+$/,"Only letters, numbers, - and _ are allowed"),config:f});b.z.union([b.z.object({mcpServers:b.z.record(b.z.string(),f)}),b.z.record(b.z.string(),f)]),a.s(["MCPServerFormSchema",0,j,"isRemoteConfig",0,function(a){return"url"in a}])},986743,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(530385),f=a.i(351674),g=a.i(203469);a.i(569572);var h=a.i(184838),i=a.i(714428),j=a.i(661210),k=b([h]);[h]=k.then?(await k)():k;let B=()=>g.appEvents.emit({type:"memory"});async function l(a,b,c={}){let[d]=await h.database.insert(i.memoryNoteTable).values({path:a,description:b,ownedByUser:c.ownedByUser??!1}).onConflictDoNothing({target:i.memoryNoteTable.path}).returning();return d&&B(),d??null}async function m(a,b){let[c]=await h.database.update(i.memoryNoteTable).set({...b,updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,a)).returning();return c&&B(),c??null}async function n(a){let b=await h.database.delete(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.id,a)).returning({id:i.memoryNoteTable.id});return b.length>0&&B(),b.length>0}async function o(a,b){let[c]=await h.database.insert(i.memoryFactTable).values({noteId:a,text:b,source:"user"}).returning();return await r(a),B(),c}async function p(a,b,c){let e=await h.database.transaction(async e=>{let f=await e.update(i.memoryFactTable).set({isLatest:!1}).where((0,d.and)((0,d.eq)(i.memoryFactTable.id,b),(0,d.eq)(i.memoryFactTable.noteId,a),(0,d.eq)(i.memoryFactTable.isLatest,!0))).returning({id:i.memoryFactTable.id});if(0===f.length)return null;let[g]=await e.insert(i.memoryFactTable).values({noteId:a,text:c,source:"user"}).returning();return await e.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,a)),g});return e&&B(),e}async function q(a,b){let c=await h.database.delete(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.id,b),(0,d.eq)(i.memoryFactTable.noteId,a))).returning({id:i.memoryFactTable.id});return c.length>0&&(await r(a),B()),c.length>0}function r(a){return h.database.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,a))}async function s(){for(let a of j.MEMORY_ALWAYS_LISTED){let b=j.MEMORY_PATHS.find(b=>b.path===a)?.of??a;await h.database.insert(i.memoryNoteTable).values({path:a,description:b}).onConflictDoUpdate({target:i.memoryNoteTable.path,set:{description:b}})}}async function t(a,b={}){let c=[...new Set(a.map(a=>a.trim()).filter(Boolean))];if(!c.length)return{notes:[],missing:[]};let g=await h.database.select({id:i.memoryNoteTable.id,path:i.memoryNoteTable.path,description:i.memoryNoteTable.description}).from(i.memoryNoteTable).where((0,d.inArray)(i.memoryNoteTable.path,c)),j=new Map(g.map(a=>[a.path,a])),k=c.filter(a=>!j.has(a));if(!g.length)return{notes:[],missing:k};let l=g.map(a=>a.id),m=await h.database.select({id:i.memoryFactTable.id,noteId:i.memoryFactTable.noteId,text:i.memoryFactTable.text,source:i.memoryFactTable.source,createdAt:i.memoryFactTable.createdAt,saidAt:i.callTable.startedAt}).from(i.memoryFactTable).leftJoin(i.callTable,(0,d.eq)(i.memoryFactTable.callId,i.callTable.id)).where((0,d.and)((0,d.eq)(i.memoryFactTable.isLatest,!0),(0,d.inArray)(i.memoryFactTable.noteId,l))).orderBy((0,e.asc)(i.memoryFactTable.id));return!1!==b.touch&&await h.database.update(i.memoryNoteTable).set({hits:f.sql`${i.memoryNoteTable.hits} + 1`,lastReadAt:new Date}).where((0,d.inArray)(i.memoryNoteTable.id,l)),{notes:c.flatMap(a=>{let b=j.get(a);return b?[{path:b.path,description:b.description,facts:m.filter(a=>a.noteId===b.id).map(a=>({id:a.id,text:a.text,...a.saidAt?{saidAt:a.saidAt}:{}}))}]:[]}),missing:k}}(0,d.inArray)(i.memoryNoteTable.path,j.MEMORY_ALWAYS_LISTED);let C=a=>a.toLowerCase().replace(/[\s.,!?…·'"`]/g,"");async function u(a,b,c,e,f){let g=await a.select({id:i.memoryFactTable.id,text:i.memoryFactTable.text}).from(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.noteId,b),(0,d.eq)(i.memoryFactTable.isLatest,!0))),h=new Map(g.map(a=>[C(a.text),a]));for(let g of c){let c=g.text.trim();if(!c)continue;if(null!=g.replaces){let[j]=await a.select({id:i.memoryFactTable.id,text:i.memoryFactTable.text}).from(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.id,g.replaces),(0,d.eq)(i.memoryFactTable.noteId,b),(0,d.eq)(i.memoryFactTable.isLatest,!0)));if(j){if(C(j.text)===C(c))continue;await a.update(i.memoryFactTable).set({isLatest:!1}).where((0,d.eq)(i.memoryFactTable.id,j.id)),h.delete(C(j.text));let[g]=await a.insert(i.memoryFactTable).values({noteId:b,text:c,source:e,callId:f}).returning({id:i.memoryFactTable.id});h.set(C(c),{...g,text:c});continue}}if(h.has(C(c)))continue;let[j]=await a.insert(i.memoryFactTable).values({noteId:b,text:c,source:e,callId:f}).returning({id:i.memoryFactTable.id});h.set(C(c),{...j,text:c})}await a.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,b))}async function v(a,b,c,e=null){let f=a.trim();if(!await h.database.transaction(async a=>{let[g]=await a.select({id:i.memoryNoteTable.id}).from(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.path,f));return!!g&&(await u(a,g.id,b,c,e),!0)}))return null;let{notes:g}=await t([f],{touch:!1});return B(),g[0]??null}async function w(a,b,c,d,e=null){let f=a.trim();if(!await h.database.transaction(async a=>{let[g]=await a.insert(i.memoryNoteTable).values({path:f,description:b}).onConflictDoNothing({target:i.memoryNoteTable.path}).returning({id:i.memoryNoteTable.id});return!!g&&(await u(a,g.id,c,d,e),!0)}))return null;let{notes:g}=await t([f],{touch:!1});return B(),g[0]??null}async function x(a,b){let[c]=await h.database.update(i.memoryNoteTable).set({description:b,updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.path,a.trim())).returning({id:i.memoryNoteTable.id});return c&&B(),!!c}async function y(){let[a,b]=await Promise.all([h.database.select({id:i.memoryNoteTable.id,path:i.memoryNoteTable.path,description:i.memoryNoteTable.description,hits:i.memoryNoteTable.hits,lastReadAt:i.memoryNoteTable.lastReadAt,createdAt:i.memoryNoteTable.createdAt}).from(i.memoryNoteTable),h.database.select({noteId:i.memoryFactTable.noteId,count:f.sql`count(*)`}).from(i.memoryFactTable).where((0,d.eq)(i.memoryFactTable.isLatest,!0)).groupBy(i.memoryFactTable.noteId)]),c=new Map(b.map(a=>[a.noteId,a.count]));return a.filter(a=>(0,j.isAlwaysListed)(a.path)||(c.get(a.id)??0)>0).sort((a,b)=>Number((0,j.isAlwaysListed)(b.path))-Number((0,j.isAlwaysListed)(a.path))||(0,j.recallScore)(b)-(0,j.recallScore)(a)).map(a=>({path:a.path,description:a.description,factCount:c.get(a.id)??0,lastSeenAt:a.lastReadAt??a.createdAt}))}async function z(a){let b=await h.database.transaction(async b=>{let c=await b.delete(i.memoryFactTable).where((0,d.eq)(i.memoryFactTable.id,a)).returning({noteId:i.memoryFactTable.noteId});if(0===c.length)return null;let e=c[0].noteId,[g]=await b.select({path:i.memoryNoteTable.path,ownedByUser:i.memoryNoteTable.ownedByUser}).from(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.id,e)),[h]=await b.select({count:f.sql`count(*)`}).from(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.noteId,e),(0,d.eq)(i.memoryFactTable.isLatest,!0)));return h?.count!==0||!g||g.ownedByUser||(0,j.isAlwaysListed)(g.path)?(await b.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,e)),{path:g?.path??"",noteGone:!1}):(await b.delete(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.id,e)),{path:g.path,noteGone:!0})});return b&&B(),b}async function A(){let a=await h.database.delete(i.memoryNoteTable).returning({id:i.memoryNoteTable.id});return await s(),a.length>0&&B(),a.length}a.s(["addFact",0,o,"createNote",0,l,"createNoteWithFacts",0,w,"deleteAllNotes",0,A,"deleteNote",0,n,"describeNote",0,x,"forgetFact",0,q,"forgetFactById",0,z,"listNoteIndex",0,y,"readNotes",0,t,"reviseFact",0,p,"updateNote",0,m,"writeFacts",0,v]),c()}catch(a){c(a)}},!1),661210,a=>{"use strict";var b=a.i(53112),c=a.i(569572),d=a.i(706210);let e=b.z.enum(["user","call","bot"]),f=b.z.string().trim().min(1,"A note needs a line saying what it is about").max(c.MEMORY_LIMITS.descriptionChars,`A note's line is one line: at most ${c.MEMORY_LIMITS.descriptionChars} characters`),g=b.z.object({id:b.z.number(),text:b.z.string(),source:e.nullish(),createdAt:d.DateLikeSchema});b.z.object({id:b.z.number(),path:b.z.string(),description:b.z.string(),ownedByUser:b.z.boolean(),hits:b.z.number(),lastReadAt:d.DateLikeSchema.nullable(),createdAt:d.DateLikeSchema,updatedAt:d.DateLikeSchema,factCount:b.z.number(),facts:g.array()});let h=[{path:"profile",of:"The user themselves — name, age, what they do, where they live, whatever else says who they are"},{path:"preferences",of:"How they want things done, and said — read whole on every call, so a rule for a particular situation goes here too"},{path:"people/",of:"Someone in their life, and what matters about them"},{path:"projects/",of:"Something with an end — a trip, a purchase, a deadline, a thing being built"},{path:"topics/",of:"Something ongoing that keeps coming back"}],i=h.filter(a=>!a.path.endsWith("/")).map(a=>a.path),j=h.filter(a=>a.path.endsWith("/")).map(a=>a.path.slice(0,-1)),k=RegExp(`^(?:${i.join("|")}|(?:${j.join("|")})/.+)$`);a.s(["MEMORY_ALWAYS_LISTED",0,i,"MEMORY_PATHS",0,h,"NoteLineSchema",0,f,"isAlwaysListed",0,a=>i.includes(a),"isMemoryPath",0,a=>k.test(a),"recallScore",0,function(a){let b=(0,d.toDate)(a.lastReadAt??a.createdAt),c=Math.max(0,(Date.now()-b.getTime())/864e5);return(a.hits+1)/(1+c)}])},780946,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(258261),f=a.i(530385),g=a.i(203469),h=a.i(569572),i=a.i(184838),j=a.i(714428),k=a.i(221214),l=a.i(293480),m=a.i(643020),n=b([i,k]);[i,k]=n.then?(await n)():n;let z=()=>g.appEvents.emit({type:"routines"});async function o(a,b){return i.database.select({id:j.threadTable.id,status:j.threadTable.status,outcome:j.threadTable.outcome,updatedAt:j.threadTable.updatedAt}).from(j.threadTable).where((0,d.eq)(j.threadTable.routineId,a)).orderBy((0,f.desc)(j.threadTable.createdAt)).limit(b)}let A=async a=>{let{createdAt:b,...c}=a;return{...c,runs:await o(a.id,h.ROUTINE.runsShown)}};async function p(){let a=await i.database.select().from(j.routineTable).orderBy(j.routineTable.createdAt);return Promise.all(a.map(A))}async function q(a){let[b]=await i.database.select().from(j.routineTable).where((0,d.eq)(j.routineTable.id,a));return b?A(b):null}async function r(a){let b=await q(a.trim());if(b)return b;let c=a.trim().toLowerCase(),d=(await p()).filter(a=>a.label.toLowerCase()===c);return 1===d.length?d[0]:null}async function s(a){let b=await (0,k.findJobBot)(a);return(!b||b.disabled)&&(0,l.publicError)("Choose an enabled bot."),b.name}function t(a,b){b&&"once"===a.kind&&(0,m.momentOf)(a.at)<=new Date&&(0,l.publicError)("That time has passed. Pick a later one.")}async function u(a){let[{total:b}]=await i.database.select({total:(0,e.count)()}).from(j.routineTable);b>=h.ROUTINE.max&&(0,l.publicError)(`There are already ${h.ROUTINE.max} routines. Delete one to make another.`),t(a.schedule,!0);let[c]=await i.database.insert(j.routineTable).values({id:crypto.randomUUID(),...a,bot:await s(a.bot),nextRunAt:(0,m.nextRun)(a.schedule,new Date)}).returning();return z(),A(c)}async function v(a,b){let[c]=await i.database.select().from(j.routineTable).where((0,d.eq)(j.routineTable.id,a));if(!c)return null;let e=b.schedule??c.schedule,f=!!(b.schedule&&!(0,m.sameSchedule)(b.schedule,c.schedule))||b.enabled&&!c.enabled;f&&t(e,b.enabled??c.enabled);let[g]=await i.database.update(j.routineTable).set({...b,...b.bot?{bot:await s(b.bot)}:{},...f?{nextRunAt:(0,m.nextRun)(e,new Date)}:{}}).where((0,d.eq)(j.routineTable.id,a)).returning();return z(),A(g)}async function w(a){let b=await i.database.delete(j.routineTable).where((0,d.eq)(j.routineTable.id,a)).returning({id:j.routineTable.id});return b.length&&z(),b.length>0}async function x(a){return(await o(a,1))[0]??null}async function y(a){return(await i.database.select({id:j.threadTable.id}).from(j.threadTable).where((0,d.and)((0,d.eq)(j.threadTable.routineId,a),(0,d.eq)(j.threadTable.seen,!1),(0,d.inArray)(j.threadTable.status,["done","cancelled"])))).map(a=>a.id)}a.s(["createRoutine",0,u,"deleteRoutine",0,w,"findRoutine",0,q,"latestRun",0,x,"listRoutines",0,p,"listUnseenRunIds",0,y,"resolveRoutine",0,r,"updateRoutine",0,v]),c()}catch(a){c(a)}},!1),643020,a=>{"use strict";var b=a.i(723885),c=a.i(569572),d=a.i(706210);let e=b.default.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"A time is HH:MM, 00:00 to 23:59");function f(a){let[b,c]=a.split(" "),[d,e,f]=b.split("-").map(Number),[g,h]=c.split(":").map(Number);return new Date(d,e-1,f,g,h)}let g=/^\d{4}-\d\d-\d\d ([01]\d|2[0-3]):[0-5]\d$/,h=b.default.string().regex(g,'A moment is "YYYY-MM-DD HH:MM"').refine(a=>{if(!g.test(a))return!0;let b=f(a);return b.getMonth()===Number(a.slice(5,7))-1&&b.getDate()===Number(a.slice(8,10))},"There is no such day"),i=b.default.discriminatedUnion("kind",[b.default.object({kind:b.default.literal("once"),at:h}),b.default.object({kind:b.default.literal("daily"),time:e,days:b.default.array(b.default.number().int().min(1).max(7)).min(1,"Pick at least one day").transform(a=>[...new Set(a)].sort((a,b)=>a-b))}),b.default.object({kind:b.default.literal("every"),hours:b.default.number().int().min(c.ROUTINE.minHours,`No more often than every ${c.ROUTINE.minHours}h`).max(168)})]),j=b.default.object({bot:b.default.string().trim().min(1,"Pick a bot"),label:b.default.string().trim().min(1,"Give it a name").max(80),request:b.default.string().trim().min(1,"Say what it should do"),schedule:i}),k=b.default.object({id:b.default.string(),status:b.default.enum(["running","waiting","done","cancelled"]),outcome:b.default.string().nullable(),updatedAt:d.DateLikeSchema});j.extend({id:b.default.string(),enabled:b.default.boolean(),nextRunAt:d.DateLikeSchema,runs:b.default.array(k)});let l=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],m=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];a.s(["RoutineInputSchema",0,j,"RoutineScheduleSchema",0,i,"momentOf",0,f,"nextRun",0,function(a,b){if("once"===a.kind)return f(a.at);if("every"===a.kind)return new Date(b.getTime()+36e5*a.hours);let[c,d]=a.time.split(":").map(Number);for(let e=0;e<=7;e++){let f=new Date(b);f.setDate(f.getDate()+e),f.setHours(c,d,0,0);let g=0===f.getDay()?7:f.getDay();if(f>b&&a.days.includes(g))return f}return new Date(b.getTime()+864e5)},"sameSchedule",0,function(a,b){if("once"===a.kind)return"once"===b.kind&&a.at===b.at;if("every"===a.kind)return"every"===b.kind&&a.hours===b.hours;let c=a=>[...a].sort((a,b)=>a-b).join();return"daily"===b.kind&&a.time===b.time&&c(a.days)===c(b.days)},"scheduleText",0,function(a){if("once"===a.kind){let[b,c]=a.at.split(" "),[,d,e]=b.split("-").map(Number);return`Once \xb7 ${m[d-1]} ${e} ${c}`}if("every"===a.kind)return 1===a.hours?"Every hour":`Every ${a.hours} hours`;let{days:b,time:c}=a;if(7===b.length)return`Daily ${c}`;if(1===b.length)return`${l[b[0]-1]} ${c}`;let d=b.every((a,c)=>0===c||a===b[c-1]+1)?`${l[b[0]-1]}–${l[b.at(-1)-1]}`:b.map(a=>l[a-1]).join(" ");return`Daily ${c} \xb7 ${d}`}])},487591,422807,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(203469),e=a.i(569572),f=a.i(821415);a.i(176668);let g=a=>a.trim().toLowerCase().replace(/^[a-z]+:\/\//,"").replace(/^www\./,"").replace(/[/?#].*$/,"");a.s(["siteOf",0,g],422807);let h=(0,c.join)(e.DATA_DIR,e.PATHS.signIns),i=a=>(0,c.join)(h,`${encodeURIComponent(g(a))}.json`),j=()=>d.appEvents.emit({type:"signins"});async function k(a){try{return JSON.parse(await (0,b.readFile)(i(a),"utf8"))}catch{return null}}async function l(a){let b=g(a),c=await k(b);if(c)return c;let d=(await n()).map(a=>a.site).filter(a=>b.endsWith(`.${a}`)).sort((a,b)=>b.length-a.length)[0];return d?k(d):null}async function m(a){await (0,b.mkdir)(h,{recursive:!0}),await (0,b.writeFile)(i(a.site),JSON.stringify(a),{mode:384}),j()}async function n(){let a=await (0,b.readdir)(h).catch(()=>[]);return(await Promise.all(a.filter(a=>a.endsWith(".json")).map(a=>k(decodeURIComponent(a.slice(0,-5)))))).flatMap(a=>a?[(({state:a,...b})=>b)(a)]:[]).sort((a,b)=>a.site.localeCompare(b.site))}async function o(a){let b=await l(a.site);if(b&&!b.bots.includes(a.bot)){let c=b.asking.includes(a.bot)?b:{...b,asking:[...b.asking,a.bot]};return c!==b&&await m(c),{kind:"taken",signIn:(({state:a,...b})=>b)(c)}}let c=b?.site??g(a.site),d={site:c,account:a.account.trim()||c,bots:[...new Set([...b?.bots??[],a.bot])],asking:(b?.asking??[]).filter(b=>b!==a.bot),keptAt:new Date().toISOString(),usedAt:b?.usedAt??null,state:a.state};return await m(d),{kind:"kept",signIn:(({state:a,...b})=>b)(d)}}let p=globalThis.__signInsHeld??=new Map;async function q(a,b){let c=await l(a);if(!c)return{kind:"none",kept:(await n()).map(a=>a.site)};if(!c.bots.includes(b))return c.asking.includes(b)||await m({...c,asking:[...c.asking,b]}),{kind:"ask",signIn:(({state:a,...b})=>b)(c)};let d={...c,usedAt:new Date().toISOString()};return await m(d),{kind:"state",signIn:(({state:a,...b})=>b)(d),state:c.state}}async function r(a,b){return(await (0,f.listBrowsers)(a,b)).find(a=>a.name===b.PLAYWRIGHT_CLI_SESSION)??null}async function s(a,b){let c=await r(a,b);return c?c.attached?"theirs":"own":null}async function t(a,b){let c=await r(a,b);return!!c&&!c.attached&&!0===c.headed}let u=a=>`${a.name}
|
|
132
135
|
${a.domain}
|
|
@@ -135,7 +138,7 @@ ${(0,g.stringify)(a).trim()}
|
|
|
135
138
|
---
|
|
136
139
|
|
|
137
140
|
${b.trim()}
|
|
138
|
-
`},"runsHere",0,a=>{let b=function({metadata:a,platforms:b}){let c=a?.platforms;return"string"==typeof c?c.split(/[\s,]+/).filter(Boolean):b}(a);return!b?.length||b.includes(process.platform)},"setSkillOff",0,x,"skillFolderName",0,function(a){let b=a.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").slice(0,64).replace(/^-+|-+$/g,"");return b||(0,n.publicError)("That skill's name has no letters to name a folder with"),b},"splitFrontmatter",0,u,"writeCustomSkill",0,z,"writeSkillFile",0,A]),c()}catch(a){c(a)}},!1),951941,a=>{"use strict";var b=a.i(53112);let c=b.z.union([b.z.enum(["custom","default"]),b.z.templateLiteral(["kit:",b.z.string().regex(/^[\p{L}\p{N}_-]+$/u)]),b.z.templateLiteral(["own:",b.z.string().regex(/^[\p{L}\p{N}_-]+$/u)])]),d=b.z.string().trim().min(1,"Skill name is required").max(64,"Skill name is too long").regex(/^[a-z0-9][a-z0-9_-]*$/i,"Use letters, numbers, dashes and underscores only"),e=b.z.string().trim().min(1,"Skill name is required").max(64,"Skill name is too long"),f=b.z.object({name:e,description:b.z.string().trim().min(1,"Description is required"),metadata:b.z.record(b.z.string(),b.z.unknown()).optional(),disabled:b.z.boolean().optional(),platforms:b.z.array(b.z.string()).optional()}),g=f.extend({name:d,content:b.z.string().trim().min(1,"Content is required")});a.s(["SKILLS_OFF_KEY",0,"SKILLS_OFF","SkillDraftSchema",0,g,"SkillFrontmatterSchema",0,f,"SkillSourceSchema",0,c,"botOfSource",0,a=>a.startsWith("kit:")||a.startsWith("own:")?a.slice(4):null,"firstSentence",0,a=>a.trim().split(/(?<=[.。])\s|\n/)[0].trim(),"isEditableSource",0,a=>"custom"===a||a.startsWith("own:"),"parseSkillsOff",0,function(a){if(!a)return new Set;try{let b=JSON.parse(a);return new Set(Array.isArray(b)?b.filter(a=>"string"==typeof a).map(a=>a.trim().toLowerCase()):[])}catch{return new Set}}])},626550,a=>{"use strict";var b=a.i(762008);let c={[b.TOOL_NAMES.memory_recall]:"Checking your notes",[b.TOOL_NAMES.memory_create]:"Starting a note",[b.TOOL_NAMES.memory_remember]:"Noting that down",[b.TOOL_NAMES.memory_describe]:"Renaming a note",[b.TOOL_NAMES.memory_forget]:"Forgetting that",[b.TOOL_NAMES.bash]:"Doing it on this computer",[b.TOOL_NAMES.web_search]:"Searching the web",[b.TOOL_NAMES.load_skill]:"Reading how to do this",[b.TOOL_NAMES.look_at]:"Looking at the picture",[b.TOOL_NAMES.make_deck]:"Making the deck",[b.TOOL_NAMES.end_call]:"Ending the call",[b.TOOL_NAMES.routine]:"Checking your routines"};function d(a,b=28){let c=a.trim().replace(/\s+/g," ");if(c.length<=b)return c;let e=c.slice(0,b),f=e.lastIndexOf(" ");return`${(f>b/2?e.slice(0,f):e).trimEnd()}…`}let e=(a,b)=>"string"==typeof a[b]?a[b].trim():"";b.TOOL_NAMES.thread_tell,b.TOOL_NAMES.thread_answer,b.TOOL_NAMES.thread_status,b.TOOL_NAMES.thread_show,b.TOOL_NAMES.thread_cancel,b.TOOL_NAMES.thread_seen,a.s(["searchOf",0,function(a,c){if(a!==b.TOOL_NAMES.web_search)return null;try{var d;let a=JSON.parse(c);return{query:"string"==typeof a.query?a.query:null,sources:(d=a.sources,Array.isArray(d)?d.flatMap(a=>a&&"object"==typeof a&&"string"==typeof a.url?[a]:[]):[])}}catch{return null}},"startedLabel",0,function(a,c){if(a!==b.TOOL_NAMES.thread_start)return null;try{let a=JSON.parse(c);return"string"==typeof a.label?a.label:null}catch{return null}},"toolLine",0,function(a,f,g=null){let h;if(a===b.TOOL_NAMES.tool_search||a===b.TOOL_NAMES.tool_call)return"Reaching a connected service";let i=function(a){if(!a)return null;try{let b=JSON.parse(a);if(b&&"object"==typeof b&&!Array.isArray(b))return b}catch{}return null}(f);return(i&&function(a,c,f){if(a===b.TOOL_NAMES.memory_remember||a===b.TOOL_NAMES.memory_create){let f=e(c,"path"),g=function(a){if(!Array.isArray(a.facts))return null;let b=a.facts.map(a=>a&&"object"==typeof a&&"string"==typeof a.text?a.text.trim():"").filter(Boolean);return b.length?{text:b[0],more:b.length-1}:null}(c),h=a===b.TOOL_NAMES.memory_create?"Starting":"Noting";if(!f)return null;if(!g)return`${h} ${f}`;let i=g.more>0?` (+${g.more})`:"";return`${h} ${f}: ${d(g.text)}${i}`}if(a===b.TOOL_NAMES.memory_recall){let a=e(c,"path");return a?`Checking \xb7 ${a}`:null}if(a===b.TOOL_NAMES.memory_describe){let a=e(c,"path");return a?`Renaming \xb7 ${a}`:null}if(a===b.TOOL_NAMES.bash){let a=e(c,"description")||e(c,"command");return a?`On this computer \xb7 ${d(a,44)}`:null}if(a===b.TOOL_NAMES.load_skill){let a=e(c,"name");return a?`Reading the ${a} skill`:null}if(a===b.TOOL_NAMES.look_at){let a=e(c,"path");return a?`Looking at ${a.split("/").filter(Boolean).at(-1)??""}`:null}if(a===b.TOOL_NAMES.make_deck){let a=e(c,"title");return a?`Making the deck \xb7 ${d(a,44)}`:null}if(a===b.TOOL_NAMES.thread_start){let a=e(c,"bot");return a?`Handing this to ${a}`:"Handing this over"}if(a===b.TOOL_NAMES.web_search){let a=e(c,"query");return a?`Searching \xb7 ${a}`:null}if(a===b.TOOL_NAMES.routine){if("create"===c.action){let a=[e(c,"bot"),function(a){if("string"==typeof a.at&&a.at.length>=16){let[b,c]=a.at.split(" "),[d,e,f]=b.split("-").map(Number),g=new Date(d,e-1,f);if(g.toDateString()===new Date().toDateString())return`once at ${c}`;let h=g.toLocaleDateString("en-US",{month:"short",day:"numeric"});return`once, ${h} ${c}`}return"string"==typeof a.time&&a.time?`daily at ${a.time}`:"number"==typeof a.everyHours?`every ${a.everyHours} hours`:null}(c)].filter(Boolean).join(", ");return a?`Setting a routine \xb7 ${a}`:"Setting a routine"}return"change"===c.action?"Changing a routine":"delete"===c.action?"Deleting a routine":null}let g=e(c,"thread");return a===b.TOOL_NAMES.thread_tell?f?`Telling ${f}`:"Passing that on":a===b.TOOL_NAMES.thread_answer?f?`Answering ${f}`:"Answering that":a===b.TOOL_NAMES.thread_cancel?g?`Stopping ${g}`:"Stopping that":a===b.TOOL_NAMES.thread_seen?g?`Marking ${g} as read`:"Marking that as read":a===b.TOOL_NAMES.thread_show?g?`Opening ${g}`:"Opening that":a===b.TOOL_NAMES.thread_status?g&&"all"!==g.toLowerCase()?`Checking on ${g}`:"Checking on the work":null}(a,i,g))??c[a]??((h=a.indexOf("__"))<=0?null:`Reaching ${a.slice(0,h).replace(/[-_]/g," ")}`)}])},956802,a=>{"use strict";var b=a.i(874533),c=a.i(569572);let d=`on run argv
|
|
141
|
+
`},"runsHere",0,a=>{let b=function({metadata:a,platforms:b}){let c=a?.platforms;return"string"==typeof c?c.split(/[\s,]+/).filter(Boolean):b}(a);return!b?.length||b.includes(process.platform)},"setSkillOff",0,x,"skillFolderName",0,function(a){let b=a.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").slice(0,64).replace(/^-+|-+$/g,"");return b||(0,n.publicError)("That skill's name has no letters to name a folder with"),b},"splitFrontmatter",0,u,"writeCustomSkill",0,z,"writeSkillFile",0,A]),c()}catch(a){c(a)}},!1),951941,a=>{"use strict";var b=a.i(53112);let c=b.z.union([b.z.enum(["custom","default"]),b.z.templateLiteral(["kit:",b.z.string().regex(/^[\p{L}\p{N}_-]+$/u)]),b.z.templateLiteral(["own:",b.z.string().regex(/^[\p{L}\p{N}_-]+$/u)])]),d=b.z.string().trim().min(1,"Skill name is required").max(64,"Skill name is too long").regex(/^[a-z0-9][a-z0-9_-]*$/i,"Use letters, numbers, dashes and underscores only"),e=b.z.string().trim().min(1,"Skill name is required").max(64,"Skill name is too long"),f=b.z.object({name:e,description:b.z.string().trim().min(1,"Description is required"),metadata:b.z.record(b.z.string(),b.z.unknown()).optional(),disabled:b.z.boolean().optional(),platforms:b.z.array(b.z.string()).optional()}),g=f.extend({name:d,content:b.z.string().trim().min(1,"Content is required")});a.s(["SKILLS_OFF_KEY",0,"SKILLS_OFF","SkillDraftSchema",0,g,"SkillFrontmatterSchema",0,f,"SkillSourceSchema",0,c,"botOfSource",0,a=>a.startsWith("kit:")||a.startsWith("own:")?a.slice(4):null,"firstSentence",0,a=>a.trim().split(/(?<=[.。])\s|\n/)[0].trim(),"isEditableSource",0,a=>"custom"===a||a.startsWith("own:"),"parseSkillsOff",0,function(a){if(!a)return new Set;try{let b=JSON.parse(a);return new Set(Array.isArray(b)?b.filter(a=>"string"==typeof a).map(a=>a.trim().toLowerCase()):[])}catch{return new Set}}])},626550,a=>{"use strict";var b=a.i(762008);let c={[b.TOOL_NAMES.memory_recall]:"Checking your notes",[b.TOOL_NAMES.memory_create]:"Starting a note",[b.TOOL_NAMES.memory_remember]:"Noting that down",[b.TOOL_NAMES.memory_describe]:"Renaming a note",[b.TOOL_NAMES.memory_forget]:"Forgetting that",[b.TOOL_NAMES.bash]:"Doing it on this computer",[b.TOOL_NAMES.web_search]:"Searching the web",[b.TOOL_NAMES.load_skill]:"Reading how to do this",[b.TOOL_NAMES.look_at]:"Looking at the picture",[b.TOOL_NAMES.make_deck]:"Making the deck",[b.TOOL_NAMES.end_call]:"Ending the call",[b.TOOL_NAMES.look_at_screen]:"Looking at your screen",[b.TOOL_NAMES.routine]:"Checking your routines"};function d(a,b=28){let c=a.trim().replace(/\s+/g," ");if(c.length<=b)return c;let e=c.slice(0,b),f=e.lastIndexOf(" ");return`${(f>b/2?e.slice(0,f):e).trimEnd()}…`}let e=(a,b)=>"string"==typeof a[b]?a[b].trim():"";b.TOOL_NAMES.thread_tell,b.TOOL_NAMES.thread_answer,b.TOOL_NAMES.thread_status,b.TOOL_NAMES.thread_show,b.TOOL_NAMES.thread_cancel,b.TOOL_NAMES.thread_seen,a.s(["searchOf",0,function(a,c){if(a!==b.TOOL_NAMES.web_search)return null;try{var d;let a=JSON.parse(c);return{query:"string"==typeof a.query?a.query:null,sources:(d=a.sources,Array.isArray(d)?d.flatMap(a=>a&&"object"==typeof a&&"string"==typeof a.url?[a]:[]):[])}}catch{return null}},"startedLabel",0,function(a,c){if(a!==b.TOOL_NAMES.thread_start)return null;try{let a=JSON.parse(c);return"string"==typeof a.label?a.label:null}catch{return null}},"toolLine",0,function(a,f,g=null){let h;if(a===b.TOOL_NAMES.tool_search||a===b.TOOL_NAMES.tool_call)return"Reaching a connected service";let i=function(a){if(!a)return null;try{let b=JSON.parse(a);if(b&&"object"==typeof b&&!Array.isArray(b))return b}catch{}return null}(f);return(i&&function(a,c,f){if(a===b.TOOL_NAMES.memory_remember||a===b.TOOL_NAMES.memory_create){let f=e(c,"path"),g=function(a){if(!Array.isArray(a.facts))return null;let b=a.facts.map(a=>a&&"object"==typeof a&&"string"==typeof a.text?a.text.trim():"").filter(Boolean);return b.length?{text:b[0],more:b.length-1}:null}(c),h=a===b.TOOL_NAMES.memory_create?"Starting":"Noting";if(!f)return null;if(!g)return`${h} ${f}`;let i=g.more>0?` (+${g.more})`:"";return`${h} ${f}: ${d(g.text)}${i}`}if(a===b.TOOL_NAMES.memory_recall){let a=e(c,"path");return a?`Checking \xb7 ${a}`:null}if(a===b.TOOL_NAMES.memory_describe){let a=e(c,"path");return a?`Renaming \xb7 ${a}`:null}if(a===b.TOOL_NAMES.bash){let a=e(c,"description")||e(c,"command");return a?`On this computer \xb7 ${d(a,44)}`:null}if(a===b.TOOL_NAMES.load_skill){let a=e(c,"name");return a?`Reading the ${a} skill`:null}if(a===b.TOOL_NAMES.look_at){let a=e(c,"path");return a?`Looking at ${a.split("/").filter(Boolean).at(-1)??""}`:null}if(a===b.TOOL_NAMES.make_deck){let a=e(c,"title");return a?`Making the deck \xb7 ${d(a,44)}`:null}if(a===b.TOOL_NAMES.thread_start){let a=e(c,"bot");return a?`Handing this to ${a}`:"Handing this over"}if(a===b.TOOL_NAMES.web_search){let a=e(c,"query");return a?`Searching \xb7 ${a}`:null}if(a===b.TOOL_NAMES.routine){if("create"===c.action){let a=[e(c,"bot"),function(a){if("string"==typeof a.at&&a.at.length>=16){let[b,c]=a.at.split(" "),[d,e,f]=b.split("-").map(Number),g=new Date(d,e-1,f);if(g.toDateString()===new Date().toDateString())return`once at ${c}`;let h=g.toLocaleDateString("en-US",{month:"short",day:"numeric"});return`once, ${h} ${c}`}return"string"==typeof a.time&&a.time?`daily at ${a.time}`:"number"==typeof a.everyHours?`every ${a.everyHours} hours`:null}(c)].filter(Boolean).join(", ");return a?`Setting a routine \xb7 ${a}`:"Setting a routine"}return"change"===c.action?"Changing a routine":"delete"===c.action?"Deleting a routine":null}let g=e(c,"thread");return a===b.TOOL_NAMES.thread_tell?f?`Telling ${f}`:"Passing that on":a===b.TOOL_NAMES.thread_answer?f?`Answering ${f}`:"Answering that":a===b.TOOL_NAMES.thread_cancel?g?`Stopping ${g}`:"Stopping that":a===b.TOOL_NAMES.thread_seen?g?`Marking ${g} as read`:"Marking that as read":a===b.TOOL_NAMES.thread_show?g?`Opening ${g}`:"Opening that":a===b.TOOL_NAMES.thread_status?g&&"all"!==g.toLowerCase()?`Checking on ${g}`:"Checking on the work":null}(a,i,g))??c[a]??((h=a.indexOf("__"))<=0?null:`Reaching ${a.slice(0,h).replace(/[-_]/g," ")}`)}])},956802,a=>{"use strict";var b=a.i(874533),c=a.i(569572);let d=`on run argv
|
|
139
142
|
display notification (item 2 of argv) with title (item 1 of argv)
|
|
140
143
|
end run`,e=`
|
|
141
144
|
$ErrorActionPreference = 'Stop'
|
|
@@ -206,7 +209,44 @@ Content-Type: ${f}\r
|
|
|
206
209
|
`),d.content instanceof Uint8Array)yield d.content;else{let a=d.content.getReader();i=a,l.add(d.content);let b=!1;try{for(;;){let{done:c,value:d}=await a.read();if(c||k){b=c;break}yield d}}finally{i=void 0,b||await a.cancel().catch(()=>{}),a.releaseLock()}if(k)return}yield j.encode("\r\n")}yield j.encode(`--${m}--\r
|
|
207
210
|
`)}()),async dispose(a){if(k)return;k=!0;let b=i;for(let d of(null!=b&&await b.cancel(a).catch(()=>{}),c))"file"!==d.type||d.content instanceof Uint8Array||l.has(d.content)||await d.content.cancel(a).catch(()=>{})}});try{let c={method:"POST",headers:K({...b,"Content-Type":`multipart/form-data; boundary=${m}`},`ai-sdk/provider-utils/${I}`,D()),body:o.stream,duplex:"half",signal:f},i=await h(a,c),j=C(i);if(!i.ok){let b;try{b=await d({response:i,url:a,requestBodyValues:n})}catch(b){if(E(b)||g.APICallError.isInstance(b))throw b;throw new g.APICallError({message:"Failed to process error response",cause:b,statusCode:i.status,url:a,responseHeaders:j,requestBodyValues:n})}throw b.value}try{return await e({response:i,url:a,requestBodyValues:n})}catch(b){if(b instanceof Error&&(E(b)||g.APICallError.isInstance(b)))throw b;throw new g.APICallError({message:"Failed to process successful response",cause:b,statusCode:i.status,url:a,responseHeaders:j,requestBodyValues:n})}}catch(b){throw await o.dispose(b),H({error:b,url:a,requestBodyValues:n})}},bf=()=>globalThis.fetch,bg=async({url:a,headers:b,body:c,failedResponseHandler:d,successfulResponseHandler:e,abortSignal:f,fetch:g})=>await bi({url:a,headers:{"Content-Type":"application/json",...b},body:{content:JSON.stringify(c),values:c},failedResponseHandler:d,successfulResponseHandler:e,abortSignal:f,fetch:g}),bh=async({url:a,headers:b,formData:c,failedResponseHandler:d,successfulResponseHandler:e,abortSignal:f,fetch:g})=>await bi({url:a,headers:b,body:{content:c,values:Object.fromEntries(c.entries())},failedResponseHandler:d,successfulResponseHandler:e,abortSignal:f,fetch:g}),bi=async({url:a,headers:b={},body:c,successfulResponseHandler:d,failedResponseHandler:e,abortSignal:f,fetch:h=bf()})=>{try{let i=await h(a,{method:"POST",headers:K(b,`ai-sdk/provider-utils/${I}`,D()),body:c.content,signal:f}),j=C(i);if(!i.ok){let b;try{b=await e({response:i,url:a,requestBodyValues:c.values})}catch(b){if(E(b)||g.APICallError.isInstance(b))throw b;throw new g.APICallError({message:"Failed to process error response",cause:b,statusCode:i.status,url:a,responseHeaders:j,requestBodyValues:c.values})}throw b.value}try{return await d({response:i,url:a,requestBodyValues:c.values})}catch(b){if(b instanceof Error&&(E(b)||g.APICallError.isInstance(b)))throw b;throw new g.APICallError({message:"Failed to process successful response",cause:b,statusCode:i.status,url:a,responseHeaders:j,requestBodyValues:c.values})}}catch(b){throw H({error:b,url:a,requestBodyValues:c.values})}};function bj(a){return a}async function bk(a){return"function"==typeof a&&(a=a()),a}async function bl(a,{maxRetries:b,delayInMs:c,backoffFactor:d,abortSignal:e,shouldRetry:f,getDelayInMs:h,createRetryError:i},j=[]){try{return await a()}catch(n){if(E(n)||0===b)throw n;let k=(0,g.getErrorMessage)(n),l=[...j,n],m=l.length;if(m>b)throw i({message:`Failed after ${m} attempts. Last error: ${k}`,reason:"maxRetriesExceeded",errors:l});if(await f(n)&&m<=b)return await q(h({error:n,exponentialBackoffDelay:c}),{abortSignal:e}),bl(a,{maxRetries:b,delayInMs:d*c,backoffFactor:d,abortSignal:e,shouldRetry:f,getDelayInMs:h,createRetryError:i},l);if(1===m)throw n;throw i({message:`Failed after ${m} attempts with non-retryable error: '${k}'`,reason:"errorNotRetryable",errors:l})}}var bm=new TextDecoder;function bn({stream:a,url:b,requestBodyValues:c,statusCode:d,responseHeaders:e}){let f=a.getReader(),h=!1,i=()=>{h||(f.releaseLock(),h=!0)};return new ReadableStream({async pull(a){try{let{done:b,value:c}=await f.read();b?(i(),a.close()):a.enqueue(c)}catch(f){if(i(),E(f))return void a.error(f);a.error(H({error:new g.APICallError({message:"Failed to process successful response",cause:f,statusCode:d,url:b,responseHeaders:e,requestBodyValues:c}),url:b,requestBodyValues:c}))}},async cancel(a){try{await f.cancel(a)}finally{i()}}})}async function bo({response:a,url:b}){return bm.decode(await an({response:a,url:b}))}async function*bp({stream:a,schema:b}){let c=a.getReader(),d=new TextDecoder,e="",f=!1;try{for(;;){let{done:a,value:g}=await c.read();if(a){f=!0,e+=d.decode();break}let h=(e+=d.decode(g,{stream:!0})).indexOf("\n");for(;-1!==h;){let a=e.slice(0,h).replace(/\r$/,"");e=e.slice(h+1),a.trim().length>0&&(yield await a8({text:a,schema:b})),h=e.indexOf("\n")}}let a=e.replace(/\r$/,"");a.trim().length>0&&(yield await a8({text:a,schema:b}))}finally{f||await c.cancel().catch(()=>{}),c.releaseLock()}}function bq(a){if(null==a)return!0;let b=typeof a;return"string"===b||"number"===b||"boolean"===b||"function"!==b&&"symbol"!==b&&"bigint"!==b&&(Array.isArray(a)?a.every(bq):Object.getPrototypeOf(a)===Object.prototype&&Object.values(a).every(bq))}var br="AI_SerializationError",bs=`vercel.ai.error.${br}`,bt=Symbol.for(bs),bu=class extends(f=g.AISDKError,e=bt,f){constructor({message:a="Failed to serialize value.",cause:b}={}){super({name:br,message:a,cause:b}),this[e]=!0}static isInstance(a){return g.AISDKError.hasMarker(a,bs)}},bv=class{constructor(a,b={}){var c,d;this.toolCalls=new Set,this.toolCallsById=new Map,this.toolCallsByIndex=new Map,this.controller=a,this._generateId=null!=(c=b.generateId)?c:as,this.typeValidation=null!=(d=b.typeValidation)?d:"none",this.extractMetadata=b.extractMetadata,this.buildToolCallProviderMetadata=b.buildToolCallProviderMetadata}processDelta(a){let{id:b,index:c}=a,d=null!=b&&b.length>0?this.toolCallsById.get(b):null!=c?this.toolCallsByIndex.get(c):this.latestToolCall;null==d?d=this.processNewToolCall(a):this.processExistingToolCall(d,a),null!=c&&this.toolCallsByIndex.set(c,d),this.latestToolCall=d}flush(){for(let a of this.toolCalls)a.hasFinished||this.finishToolCall(a)}processNewToolCall(a){var b,c,d;if("required"===this.typeValidation){if("function"!==a.type)throw new g.InvalidResponseDataError({data:a,message:"Expected 'function' type."})}else if("if-present"===this.typeValidation&&null!=a.type&&"function"!==a.type)throw new g.InvalidResponseDataError({data:a,message:"Expected 'function' type."});if(null==a.id)throw new g.InvalidResponseDataError({data:a,message:"Expected 'id' to be a string."});if((null==(b=a.function)?void 0:b.name)==null)throw new g.InvalidResponseDataError({data:a,message:"Expected 'function.name' to be a string."});this.controller.enqueue({type:"tool-input-start",id:a.id,toolName:a.function.name});let e=null==(c=this.extractMetadata)?void 0:c.call(this,a),f={id:a.id,type:"function",function:{name:a.function.name,arguments:null!=(d=a.function.arguments)?d:""},hasFinished:!1,metadata:e};return this.toolCalls.add(f),f.id.length>0&&this.toolCallsById.set(f.id,f),f.function.arguments.length>0&&this.controller.enqueue({type:"tool-input-delta",id:f.id,delta:f.function.arguments}),f}processExistingToolCall(a,b){var c;a.hasFinished||(null==(c=b.function)?void 0:c.arguments)!=null&&(a.function.arguments+=b.function.arguments,this.controller.enqueue({type:"tool-input-delta",id:a.id,delta:b.function.arguments}))}finishToolCall(a){var b,c;this.controller.enqueue({type:"tool-input-end",id:a.id});let d=null==(b=this.buildToolCallProviderMetadata)?void 0:b.call(this,a.metadata);this.controller.enqueue({type:"tool-call",toolCallId:null!=(c=a.id)?c:this._generateId(),toolName:a.function.name,input:a.function.arguments,...d?{providerMetadata:d}:{}}),a.hasFinished=!0}};function bw(a){return"string"==typeof a}function bx(a){return"number"==typeof a}function by(a,b){return void 0===a||b(a)}function bz(a){return av(a)&&bw(a.type)}function bA(a){return av(a)&&bw(a.text)&&bx(a.startSecond)&&bx(a.endSecond)}async function*bB({tool:a,input:b,options:c}){let d=a.execute(b,c);if(null!=d&&"function"==typeof d[Symbol.asyncIterator]){let a;for await(let b of d)a=b,yield{type:"preliminary",output:b};yield{type:"final",output:a}}else yield{type:"final",output:await d}}a.s(["DEFAULT_MAX_DOWNLOAD_SIZE",0,0x80000000,"DelayedPromise",0,B,"DownloadError",0,_,"EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL",0,ap,"EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER",0,aq,"EXPERIMENTAL_TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE",0,"transcription-stream.audio-done","EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE",0,"transcription-stream.start","StreamingToolCallTracker",0,bv,"asArray",0,function(a){return void 0===a?[]:Array.isArray(a)?a:[a]},"asSchema",0,a4,"cancelResponseBody",0,X,"combineHeaders",0,function(...a){return a.reduce((a,b)=>({...a,...b}),{})},"connectToWebSocket",0,function({url:a,protocols:b,headers:c,webSocket:d,abortSignal:e,onOpen:f,onMessageText:g,onProcessingError:h,onSocketError:i,onClose:j,onAbort:k}){var l,m;let n,o,p=a=>{null!=o&&(null==e||e.removeEventListener("abort",o),o=void 0);try{null==n||n.close(a)}catch(a){}};if(null==e?void 0:e.aborted)return null==k||k(null!=(l=e.reason)?l:Error("Aborted")),{socket:void 0,close:p};try{n=new(function(a){let b=null!=a?a:globalThis.WebSocket;if(null==b)throw Error("No WebSocket implementation available.");return b}(d))(a,b,{headers:(m=null!=c?c:{},Object.fromEntries(Object.entries(m).filter(([a,b])=>null!=b)))})}catch(a){return h(a),{socket:void 0,close:p}}null!=e&&null!=k&&(o=()=>{var a;return k(null!=(a=e.reason)?a:Error("Aborted"))},e.addEventListener("abort",o,{once:!0}));let q=n;n.onopen=()=>{try{null==f||f(q)}catch(a){h(a)}};let r=Promise.resolve();return n.onmessage=a=>{r=r.then(()=>t(a.data)).then(a=>g(a)).catch(h)},n.onerror=()=>{r=r.then(()=>null==i?void 0:i()).catch(h)},n.onclose=a=>{let b="number"==typeof(null==a?void 0:a.code)?a.code:void 0,c="string"==typeof(null==a?void 0:a.reason)?a.reason:void 0;r=r.then(()=>null==j?void 0:j({code:b,reason:c})).catch(h)},{socket:n,close:p}},"convertAsyncIteratorToReadableStream",0,v,"convertBase64ToUint8Array",0,y,"convertImageModelFileToDataUri",0,function(a){return"url"===a.type?a.url:`data:${a.mediaType};base64,${"string"==typeof a.data?a.data:z(a.data)}`},"convertInlineFileDataToUint8Array",0,function(a){if("stream"===a.type){let b=new g.UnsupportedFunctionalityError({functionality:"streaming file upload"});throw a.stream.cancel(b).catch(()=>{}),b}return"text"===a.type?new TextEncoder().encode(a.text):a.data instanceof Uint8Array?a.data:a.data instanceof ArrayBuffer?new Uint8Array(a.data):y(a.data)},"convertToBase64",0,function(a){return a instanceof Uint8Array?z(a):a},"convertToFormData",0,function(a,b={}){let{useArrayBrackets:c=!0}=b,d=new FormData;for(let[b,e]of Object.entries(a))if(null!=e){if(Array.isArray(e)){if(1===e.length){d.append(b,e[0]);continue}let a=c?`${b}[]`:b;for(let b of e)d.append(a,b);continue}d.append(b,e)}return d},"convertUint8ArrayToBase64",0,z,"createBinaryResponseHandler",0,()=>async({response:a,url:b,requestBodyValues:c})=>{let d=C(a);if(!a.body)throw new g.APICallError({message:"Response body is empty",url:b,requestBodyValues:c,statusCode:a.status,responseHeaders:d,responseBody:void 0});try{let b=await a.arrayBuffer();return{responseHeaders:d,value:new Uint8Array(b)}}catch(e){throw new g.APICallError({message:"Failed to read response as array buffer",url:b,requestBodyValues:c,statusCode:a.status,responseHeaders:d,responseBody:void 0,cause:e})}},"createBinaryStreamResponseHandler",0,()=>async({response:a,url:b,requestBodyValues:c})=>{let d=C(a);if(null==a.body)throw new g.EmptyResponseBodyError({});return{responseHeaders:d,value:bn({stream:a.body,url:b,requestBodyValues:c,statusCode:a.status,responseHeaders:d})}},"createEventSourceResponseHandler",0,a=>async({response:b,url:c,requestBodyValues:d})=>{let e=C(b);if(null==b.body)throw new g.EmptyResponseBodyError({});return{responseHeaders:e,value:ba({stream:bn({stream:b.body,url:c,requestBodyValues:d,statusCode:b.status,responseHeaders:e}),schema:a})}},"createIdGenerator",0,ar,"createJsonErrorResponseHandler",0,({errorSchema:a,errorToMessage:b,isRetryable:c})=>async({response:d,url:e,requestBodyValues:f})=>{let h=await bo({response:d,url:e}),i=C(d);if(""===h.trim())return{responseHeaders:i,value:new g.APICallError({message:d.statusText,url:e,requestBodyValues:f,statusCode:d.status,responseHeaders:i,responseBody:h,isRetryable:null==c?void 0:c(d)})};try{let j=await a8({text:h,schema:a});return{responseHeaders:i,value:new g.APICallError({message:b(j),url:e,requestBodyValues:f,statusCode:d.status,responseHeaders:i,responseBody:h,data:j,isRetryable:null==c?void 0:c(d,j)})}}catch(a){return{responseHeaders:i,value:new g.APICallError({message:d.statusText,url:e,requestBodyValues:f,statusCode:d.status,responseHeaders:i,responseBody:h,isRetryable:null==c?void 0:c(d)})}}},"createJsonLinesResponseHandler",0,a=>async({response:b})=>{let c=C(b);if(null==b.body)throw new g.EmptyResponseBodyError({});return{responseHeaders:c,value:bp({stream:b.body,schema:a})}},"createJsonResponseHandler",0,a=>async({response:b,url:c,requestBodyValues:d})=>{let e=await bo({response:b,url:c}),f=await a9({text:e,schema:a}),h=C(b);if(!f.success)throw new g.APICallError({message:"Invalid JSON response",cause:f.error,statusCode:b.status,responseHeaders:h,responseBody:e,url:c,requestBodyValues:d});return{responseHeaders:h,value:f.value,rawValue:f.rawValue}},"createLanguageModelResponseMetadata",0,function({id:a,model:b,created:c}){return{id:null!=a?a:void 0,modelId:null!=b?b:void 0,timestamp:null!=c?new Date(1e3*c):void 0}},"createNullLanguageModelUsage",0,function(){return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0}},"createProviderDefinedToolFactory",0,function({id:a,inputSchema:b}){return({execute:c,outputSchema:d,needsApproval:e,toModelOutput:f,onInputStart:g,onInputDelta:h,onInputAvailable:i,...j})=>bj({type:"provider",isProviderExecuted:!1,id:a,args:j,inputSchema:b,outputSchema:d,execute:c,needsApproval:e,toModelOutput:f,onInputStart:g,onInputDelta:h,onInputAvailable:i})},"createProviderDefinedToolFactoryWithOutputSchema",0,function({id:a,inputSchema:b,outputSchema:c}){return({execute:d,needsApproval:e,toModelOutput:f,onInputStart:g,onInputDelta:h,onInputAvailable:i,...j})=>bj({type:"provider",isProviderExecuted:!1,id:a,args:j,inputSchema:b,outputSchema:c,execute:d,needsApproval:e,toModelOutput:f,onInputStart:g,onInputDelta:h,onInputAvailable:i})},"createProviderExecutedToolFactory",0,function({id:a,inputSchema:b,outputSchema:c,supportsDeferredResults:d}){return({onInputStart:e,onInputDelta:f,onInputAvailable:g,...h})=>bj({type:"provider",isProviderExecuted:!0,id:a,args:h,inputSchema:b,outputSchema:c,onInputStart:e,onInputDelta:f,onInputAvailable:g,supportsDeferredResults:d})},"createProviderStreamError",0,function({message:a,type:b,code:c,statusCode:d,isRetryable:e,data:f}){let g={message:a,type:b,code:c,statusCode:d,isRetryable:e,data:f};return Object.defineProperty(g,A,{value:!0}),g},"createStatusCodeErrorResponseHandler",0,()=>async({response:a,url:b,requestBodyValues:c})=>{let d=C(a),e=await bo({response:a,url:b});return{responseHeaders:d,value:new g.APICallError({message:a.statusText,url:b,requestBodyValues:c,statusCode:a.status,responseHeaders:d,responseBody:e})}},"createToolNameMapping",0,function({tools:a=[],providerToolNames:b}){let c={},d={};for(let e of a)if("provider"===e.type&&e.id in b){let a=b[e.id];c[e.name]=a,d[a]=e.name}return{toProviderToolName:a=>{var b;return null!=(b=c[a])?b:a},toCustomToolName:a=>{var b;return null!=(b=d[a])?b:a}}},"delay",0,q,"deleteFromApi",0,M,"detectMediaType",0,U,"downloadBlob",0,ao,"dynamicTool",0,function(a){return{...a,type:"dynamic"}},"executeTool",0,bB,"experimental_getToolCaller",0,function(a){return null==a?void 0:a.experimental_toolCaller},"experimental_parseTranscriptionStreamPart",0,function(a){let b;try{b=aB(a)}catch(a){return}if(null==b||"object"!=typeof b||Array.isArray(b))return;let c=b;switch(c.type){case"stream-start":return Array.isArray(c.warnings)&&c.warnings.every(bz)?c:void 0;case"transcript-delta":return bw(c.delta)&&by(c.id,bw)&&by(c.providerMetadata,av)?c:void 0;case"transcript-partial":return bw(c.text)&&by(c.id,bw)&&by(c.startSecond,bx)&&by(c.durationInSeconds,bx)&&by(c.channelIndex,bx)&&by(c.providerMetadata,av)?c:void 0;case"transcript-final":return bw(c.text)&&by(c.id,bw)&&by(c.startSecond,bx)&&by(c.endSecond,bx)&&by(c.channelIndex,bx)&&by(c.providerMetadata,av)?c:void 0;case"finish":return bw(c.text)&&Array.isArray(c.segments)&&c.segments.every(bA)&&by(c.language,bw)&&by(c.durationInSeconds,bx)&&by(c.providerMetadata,av)?c:void 0;case"response-metadata":{if(!(by(c.modelId,bw)&&by(c.headers,av)))return;let a=c.timestamp;if(null==a)return{...c,timestamp:void 0};if("string"!=typeof a)return;let b=new Date(a);return Number.isNaN(b.getTime())?void 0:{...c,timestamp:b}}case"raw":return"rawValue"in c?c:void 0;case"error":return"error"in c?c:void 0;default:return}},"experimental_toolCaller",0,function(a,b){return Object.defineProperty({...a},"experimental_toolCaller",{value:b})},"extractResponseHeaders",0,C,"fetchWithValidatedEndpoint",0,al,"fetchWithValidatedRedirects",0,am,"filterNullable",0,function(...a){return a.filter(a=>null!=a)},"generateId",0,as,"getFromApi",0,at,"getRuntimeEnvironmentUserAgent",0,D,"getTopLevelMediaType",0,V,"injectJsonInstructionIntoMessages",0,function({messages:a,schema:b,schemaPrefix:c,schemaSuffix:d}){var e,f;let g=(null==(e=a[0])?void 0:e.role)==="system"?{...a[0]}:{role:"system",content:""};return g.content=function({prompt:a,schema:b,schemaPrefix:c=null!=b?"JSON schema:":void 0,schemaSuffix:d=null!=b?"You MUST answer with a JSON object that matches the JSON schema above.":"You MUST answer with JSON."}){return[null!=a&&a.length>0?a:void 0,null!=a&&a.length>0?"":void 0,c,null!=b?JSON.stringify(b):void 0,d].filter(a=>null!=a).join("\n")}({prompt:g.content,schema:b,schemaPrefix:c,schemaSuffix:d}),[g,...(null==(f=a[0])?void 0:f.role)==="system"?a.slice(1):a]},"isAbortError",0,E,"isBuffer",0,au,"isCustomReasoning",0,function(a){return void 0!==a&&"provider-default"!==a},"isExecutableTool",0,function(a){return null!=a&&"function"==typeof a.execute},"isFullMediaType",0,W,"isNonNullable",0,function(a){return null!=a},"isProviderReference",0,function(a){return"object"==typeof a&&null!==a&&!(a instanceof Uint8Array)&&!(a instanceof URL)&&!(a instanceof ArrayBuffer)&&!au(a)&&!("type"in a)},"isProviderStreamError",0,function(a){return"object"==typeof a&&null!=a&&!0===a[A]},"isRecord",0,av,"isSameOrigin",0,aa,"isUrlSupported",0,function({mediaType:a,url:b,supportedUrls:c}){b=b.toLowerCase();let d=!(a=a.toLowerCase()).includes("/");return Object.entries(c).map(([a,b])=>{let c=a.toLowerCase();return"*"===c||"*/*"===c?{mediaTypePrefix:"",regexes:b}:{mediaTypePrefix:c.replace(/\*/,""),regexes:b}}).filter(({mediaTypePrefix:b})=>""===b||(d?`${a}/`===b:a.startsWith(b))).flatMap(({regexes:a})=>a).some(a=>(function(a,b){if(!a.global&&!a.sticky)return a.test(b);let c=a.lastIndex;a.lastIndex=0;try{return a.test(b)}finally{a.lastIndex=c}})(a,b))},"jsonSchema",0,a3,"lazySchema",0,function(a){let b;return()=>(null==b&&(b=a()),b)},"loadApiKey",0,function({apiKey:a,environmentVariableName:b,apiKeyParameterName:c="apiKey",description:d}){if("string"==typeof a)return a;if(null!=a)throw new g.LoadAPIKeyError({message:`${d} API key must be a string.`});if("u"<typeof process)throw new g.LoadAPIKeyError({message:`${d} API key is missing. Pass it using the '${c}' parameter. Environment variables are not supported in this environment.`});if(null==(a=process.env[b]))throw new g.LoadAPIKeyError({message:`${d} API key is missing. Pass it using the '${c}' parameter or the ${b} environment variable.`});if("string"!=typeof a)throw new g.LoadAPIKeyError({message:`${d} API key must be a string. The value of the ${b} environment variable is not a string.`});return a},"loadOptionalSetting",0,function({settingValue:a,environmentVariableName:b}){return"string"==typeof a?a:null!=a||"u"<typeof process?void 0:null!=(a=process.env[b])&&"string"==typeof a?a:void 0},"mapReasoningToProviderBudget",0,function({reasoning:a,maxOutputTokens:b,maxReasoningBudget:c,minReasoningBudget:d=1024,budgetPercentages:e=aw,warnings:f}){let g=e[a];return null==g?void f.push({type:"unsupported",feature:"reasoning",details:`reasoning "${a}" is not supported by this model.`}):Math.min(c,Math.max(d,Math.round(b*g)))},"mapReasoningToProviderEffort",0,function({reasoning:a,effortMap:b,warnings:c}){let d=b[a];return null==d?void c.push({type:"unsupported",feature:"reasoning",details:`reasoning "${a}" is not supported by this model.`}):(d!==a&&c.push({type:"compatibility",feature:"reasoning",details:`reasoning "${a}" is not directly supported by this model. mapped to effort "${d}".`}),d)},"mediaTypeToExtension",0,function(a){var b;let[c,d=""]=a.toLowerCase().split("/");return null!=(b=({mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"})[d])?b:d},"normalizeBatchRequestCounts",0,function({total:a,pending:b,completed:c,failed:d}){if(ax(a)&&ax(b)&&ax(c)&&ax(d)&&b+c+d===a)return{total:a,pending:b,completed:c,failed:d}},"normalizeHeaders",0,J,"parseJSON",0,a8,"parseJsonEventStream",0,ba,"parseProviderOptions",0,bb,"postFormDataToApi",0,bh,"postJsonToApi",0,bg,"postMultipartStreamToApi",0,be,"postToApi",0,bi,"readResponseWithSizeLimit",0,an,"resolve",0,bk,"resolveFullMediaType",0,function({part:a}){if(W(a.mediaType))return a.mediaType;if("data"===a.data.type){let b=U({data:a.data.data,topLevelType:V(a.mediaType)});if(b)return b;throw new g.UnsupportedFunctionalityError({functionality:`file of media type "${a.mediaType}" must specify subtype since it could not be auto-detected`})}throw new g.UnsupportedFunctionalityError({functionality:`file of media type "${a.mediaType}" must specify subtype since it is not passed as inline bytes`})},"resolveProviderReference",0,function({reference:a,provider:b}){let c=a[b];if(null!=c)return c;throw new g.NoSuchProviderReferenceError({provider:b,reference:a})},"retryWithExponentialBackoff",0,({maxRetries:a=2,initialDelayInMs:b=2e3,backoffFactor:c=2,abortSignal:d,shouldRetry:e,getDelayInMs:f=({exponentialBackoffDelay:a})=>a,createRetryError:g=({message:a})=>Error(a)})=>async h=>bl(h,{maxRetries:a,delayInMs:b,backoffFactor:c,abortSignal:d,shouldRetry:e,getDelayInMs:f,createRetryError:g}),"safeParseJSON",0,a9,"safeValidateTypes",0,a7,"secureJsonParse",0,aB,"serializeModelOptions",0,function(a){let b={};for(let[c,d]of Object.entries(a.config))if("headers"===c){let a=function(a){let b=a;if("function"==typeof a&&(b=a()),b instanceof Promise)throw new bu({message:"Cannot serialize asynchronous model options."});return b}(d);bq(a)&&(b[c]=a)}else bq(d)&&(b[c]=d);return{modelId:a.modelId,config:b}},"toWebSocketUrl",0,function(a){let b=new URL(a);return"http:"===b.protocol?b.protocol="ws:":"https:"===b.protocol&&(b.protocol="wss:"),b},"tool",0,bj,"validateBaseURL",0,function(a){if((null==a?void 0:a.trim())==="")throw new g.InvalidArgumentError({argument:"baseURL",message:"baseURL must be a non-empty string."});return a},"validateDownloadUrl",0,ab,"validateTypes",0,a6,"waitForWebSocketBufferDrain",0,u,"withUserAgentSuffix",0,K,"withoutTrailingSlash",0,function(a){return null==a?void 0:a.replace(/\/$/,"")},"zodSchema",0,a5],527990)},652685,a=>{"use strict";var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H="vercel.ai.error",I=Symbol.for(H),J=class a extends(c=Error,b=I,c){constructor({name:a,message:c,cause:d}){super(c),this[b]=!0,this.name=a,this.cause=d}static isInstance(b){return a.hasMarker(b,H)}static hasMarker(a,b){let c=Symbol.for(b);return null!=a&&"object"==typeof a&&c in a&&"boolean"==typeof a[c]&&!0===a[c]}},K="AI_APICallError",L=`vercel.ai.error.${K}`,M=Symbol.for(L),N=class extends(e=J,d=M,e){constructor({message:a,url:b,requestBodyValues:c,statusCode:e,responseHeaders:f,responseBody:g,cause:h,isRetryable:i=null!=e&&(408===e||409===e||429===e||e>=500),data:j}){super({name:K,message:a,cause:h}),this[d]=!0,this.url=b,this.requestBodyValues=c,this.statusCode=e,this.responseHeaders=f,this.responseBody=g,this.isRetryable=i,this.data=j}static isInstance(a){return J.hasMarker(a,L)}},O="AI_EmptyResponseBodyError",P=`vercel.ai.error.${O}`,Q=Symbol.for(P),R=class extends(g=J,f=Q,g){constructor({message:a="Empty response body"}={}){super({name:O,message:a}),this[f]=!0}static isInstance(a){return J.hasMarker(a,P)}},S="AI_EvaluationUnsupportedQuestionTypeError",T=`vercel.ai.error.${S}`,U=Symbol.for(T),V=class extends(i=J,h=U,i){constructor({questionId:a,questionType:b,provider:c,modelId:d,message:e=`Question "${a}" has type "${b}", which is not supported by provider "${c}" and model "${d}".`}){super({name:S,message:e}),this[h]=!0,this.questionId=a,this.questionType=b,this.provider=c,this.modelId=d}static isInstance(a){return J.hasMarker(a,T)}};function W(a){return null==a?"unknown error":"string"==typeof a?a:a instanceof Error?a.toString():JSON.stringify(a)}var X="AI_InvalidArgumentError",Y=`vercel.ai.error.${X}`,Z=Symbol.for(Y),$=class extends(k=J,j=Z,k){constructor({message:a,cause:b,argument:c}){super({name:X,message:a,cause:b}),this[j]=!0,this.argument=c}static isInstance(a){return J.hasMarker(a,Y)}},_="AI_InvalidPromptError",aa=`vercel.ai.error.${_}`,ab=Symbol.for(aa),ac=class extends(m=J,l=ab,m){constructor({prompt:a,message:b,cause:c}){super({name:_,message:`Invalid prompt: ${b}`,cause:c}),this[l]=!0,this.prompt=a}static isInstance(a){return J.hasMarker(a,aa)}},ad="AI_InvalidResponseDataError",ae=`vercel.ai.error.${ad}`,af=Symbol.for(ae),ag=class extends(o=J,n=af,o){constructor({data:a,message:b=`Invalid response data: ${JSON.stringify(a)}.`}){super({name:ad,message:b}),this[n]=!0,this.data=a}static isInstance(a){return J.hasMarker(a,ae)}},ah="AI_JSONParseError",ai=`vercel.ai.error.${ah}`,aj=Symbol.for(ai),ak=class extends(q=J,p=aj,q){constructor({text:a,cause:b}){super({name:ah,message:`JSON parsing failed: Text: ${a}.
|
|
208
211
|
Error message: ${W(b)}`,cause:b}),this[p]=!0,this.text=a}static isInstance(a){return J.hasMarker(a,ai)}},al="AI_LoadAPIKeyError",am=`vercel.ai.error.${al}`,an=Symbol.for(am),ao=class extends(s=J,r=an,s){constructor({message:a}){super({name:al,message:a}),this[r]=!0}static isInstance(a){return J.hasMarker(a,am)}},ap="AI_LoadSettingError",aq=`vercel.ai.error.${ap}`,ar=Symbol.for(aq),as=class extends(u=J,t=ar,u){constructor({message:a}){super({name:ap,message:a}),this[t]=!0}static isInstance(a){return J.hasMarker(a,aq)}},at="AI_NoContentGeneratedError",au=`vercel.ai.error.${at}`,av=Symbol.for(au),aw=class extends(w=J,v=av,w){constructor({message:a="No content generated."}={}){super({name:at,message:a}),this[v]=!0}static isInstance(a){return J.hasMarker(a,au)}},ax="AI_NoSuchModelError",ay=`vercel.ai.error.${ax}`,az=Symbol.for(ay),aA=class extends(y=J,x=az,y){constructor({errorName:a=ax,modelId:b,modelType:c,message:d=`No such ${c}: ${b}`}){super({name:a,message:d}),this[x]=!0,this.modelId=b,this.modelType=c}static isInstance(a){return J.hasMarker(a,ay)}},aB="AI_NoSuchProviderReferenceError",aC=`vercel.ai.error.${aB}`,aD=Symbol.for(aC),aE=class extends(A=J,z=aD,A){constructor({provider:a,reference:b,message:c=`No provider reference found for provider '${a}'. Available providers: ${Object.keys(b).join(", ")}`}){super({name:aB,message:c}),this[z]=!0,this.provider=a,this.reference=b}static isInstance(a){return J.hasMarker(a,aC)}},aF="AI_TooManyEmbeddingValuesForCallError",aG=`vercel.ai.error.${aF}`,aH=Symbol.for(aG),aI=class extends(C=J,B=aH,C){constructor(a){super({name:aF,message:`Too many values for a single embedding call. The ${a.provider} model "${a.modelId}" can only embed up to ${a.maxEmbeddingsPerCall} values per call, but ${a.values.length} values were provided.`}),this[B]=!0,this.provider=a.provider,this.modelId=a.modelId,this.maxEmbeddingsPerCall=a.maxEmbeddingsPerCall,this.values=a.values}static isInstance(a){return J.hasMarker(a,aG)}},aJ="AI_TypeValidationError",aK=`vercel.ai.error.${aJ}`,aL=Symbol.for(aK),aM=class a extends(E=J,D=aL,E){constructor({value:a,cause:b,context:c}){let d="Type validation failed";if((null==c?void 0:c.field)&&(d+=` for ${c.field}`),(null==c?void 0:c.entityName)||(null==c?void 0:c.entityId)){d+=" (";const a=[];c.entityName&&a.push(c.entityName),c.entityId&&a.push(`id: "${c.entityId}"`),d+=a.join(", "),d+=")"}super({name:aJ,message:`${d}: Value: ${JSON.stringify(a)}.
|
|
209
|
-
Error message: ${W(b)}`,cause:b}),this[D]=!0,this.value=a,this.context=c}static isInstance(a){return J.hasMarker(a,aK)}static wrap({value:b,cause:c,context:d}){var e,f,g;return a.isInstance(c)&&c.value===b&&(null==(e=c.context)?void 0:e.field)===(null==d?void 0:d.field)&&(null==(f=c.context)?void 0:f.entityName)===(null==d?void 0:d.entityName)&&(null==(g=c.context)?void 0:g.entityId)===(null==d?void 0:d.entityId)?c:new a({value:b,cause:c,context:d})}},aN="AI_UnsupportedFunctionalityError",aO=`vercel.ai.error.${aN}`,aP=Symbol.for(aO),aQ=class extends(G=J,F=aP,G){constructor({functionality:a,message:b=`'${a}' functionality not supported.`}){super({name:aN,message:b}),this[F]=!0,this.functionality=a}static isInstance(a){return J.hasMarker(a,aO)}};function aR(a){return null===a||"string"==typeof a||"number"==typeof a||"boolean"==typeof a||(Array.isArray(a)?a.every(aR):"object"==typeof a&&Object.entries(a).every(([a,b])=>"string"==typeof a&&(void 0===b||aR(b))))}a.s(["AISDKError",0,J,"APICallError",0,N,"EmptyResponseBodyError",0,R,"Experimental_EvaluationUnsupportedQuestionTypeError",0,V,"InvalidArgumentError",0,$,"InvalidPromptError",0,ac,"InvalidResponseDataError",0,ag,"JSONParseError",0,ak,"LoadAPIKeyError",0,ao,"LoadSettingError",0,as,"NoContentGeneratedError",0,aw,"NoSuchModelError",0,aA,"NoSuchProviderReferenceError",0,aE,"TooManyEmbeddingValuesForCallError",0,aI,"TypeValidationError",0,aM,"UnsupportedFunctionalityError",0,aQ,"getErrorMessage",0,W,"isJSONArray",0,function(a){return Array.isArray(a)&&a.every(aR)},"isJSONObject",0,function(a){return null!=a&&"object"==typeof a&&Object.entries(a).every(([a,b])=>"string"==typeof a&&(void 0===b||aR(b)))}])},434451,a=>{"use strict";var b=a.i(404989),c=a.i(527990),d=a.i(53112),e=a.i(912735),f=(0,c.lazySchema)(()=>(0,c.zodSchema)(d.z.object({error:d.z.object({message:d.z.string()})}))),g=(0,c.lazySchema)(()=>(0,c.zodSchema)(d.z.object({id:d.z.string().nullish(),model:d.z.string().nullish(),results:d.z.array(d.z.object({index:d.z.number(),relevance_score:d.z.number()})),usage:d.z.object({prompt_tokens:d.z.number(),completion_tokens:d.z.number(),total_tokens:d.z.number()})}))),h=(0,c.lazySchema)(()=>(0,c.zodSchema)(d.z.object({rankFields:d.z.array(d.z.string()).optional()}))),i=class{constructor(a,b){this.specificationVersion="v4",this.modelId=a,this.config=b}get provider(){return this.config.provider}async doRerank({documents:a,headers:b,query:d,topN:e,abortSignal:i,providerOptions:j}){var k,l;let m=await (0,c.parseProviderOptions)({provider:"togetherai",providerOptions:j,schema:h}),{responseHeaders:n,value:o,rawValue:p}=await (0,c.postJsonToApi)({url:`${this.config.baseURL}/rerank`,headers:(0,c.combineHeaders)(this.config.headers(),b),body:{model:this.modelId,documents:a.values,query:d,top_n:e,rank_fields:null==m?void 0:m.rankFields,return_documents:!1},failedResponseHandler:(0,c.createJsonErrorResponseHandler)({errorSchema:f,errorToMessage:a=>a.error.message}),successfulResponseHandler:(0,c.createJsonResponseHandler)(g),abortSignal:i,fetch:this.config.fetch});return{ranking:o.results.map(a=>({index:a.index,relevanceScore:a.relevance_score})),response:{id:null!=(k=o.id)?k:void 0,modelId:null!=(l=o.model)?l:void 0,headers:n,body:p}}}},j=(0,c.lazySchema)(()=>(0,c.zodSchema)(d.z.looseObject({steps:d.z.number().nullish(),guidance:d.z.number().nullish(),negative_prompt:d.z.string().nullish(),disable_safety_checker:d.z.boolean().nullish()}))),k=new Set(["google/gemini-3-pro-image"]),l=class a{constructor(a,b){this.modelId=a,this.config=b,this.specificationVersion="v4",this.maxImagesPerCall=1}get provider(){return this.config.provider}static[e.WORKFLOW_SERIALIZE](a){return(0,c.serializeModelOptions)({modelId:a.modelId,config:a.config})}static[e.WORKFLOW_DESERIALIZE](b){return new a(b.modelId,b.config)}async doGenerate({prompt:a,n:b,size:d,seed:e,providerOptions:f,headers:g,abortSignal:h,files:i,mask:l}){var o,p,q,r,s;let t,u=[];if(null!=l)throw Error("Together AI does not support mask-based image editing. Use FLUX Kontext models (e.g., black-forest-labs/FLUX.1-kontext-pro) with a reference image and descriptive prompt instead.");null!=d&&u.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support the `aspectRatio` option. Use `size` instead."});let v=null!=(q=null==(p=null==(o=this.config._internal)?void 0:o.currentDate)?void 0:p.call(o))?q:new Date,w=await (0,c.parseProviderOptions)({provider:"togetherai",providerOptions:f,schema:j}),x=k.has(this.modelId),y={...w};x&&(delete y.steps,delete y.guidance,delete y.negative_prompt,delete y.disable_safety_checker,null!=e&&u.push({type:"unsupported",feature:"seed",details:`The ${this.modelId} model does not support the \`seed\` option.`})),null!=i&&i.length>0&&(t=(0,c.convertImageModelFileToDataUri)(i[0]),i.length>1&&u.push({type:"other",message:"Together AI only supports a single input image. Additional images are ignored."}));let z=null==d?void 0:d.split("x"),{value:A,responseHeaders:B}=await (0,c.postJsonToApi)({url:`${this.config.baseURL}/images/generations`,headers:(0,c.combineHeaders)(null==(s=(r=this.config).headers)?void 0:s.call(r),g),body:{model:this.modelId,prompt:a,...null!=e&&!x?{seed:e}:{},...b>1?{n:b}:{},...z&&{width:parseInt(z[0]),height:parseInt(z[1])},...null!=t?{image_url:t}:{},response_format:"base64",...y},failedResponseHandler:(0,c.createJsonErrorResponseHandler)({errorSchema:n,errorToMessage:a=>a.error.message}),successfulResponseHandler:(0,c.createJsonResponseHandler)(m),abortSignal:h,fetch:this.config.fetch});return{images:A.data.map(a=>a.b64_json),warnings:u,response:{timestamp:v,modelId:this.modelId,headers:B}}}},m=d.z.object({data:d.z.array(d.z.object({b64_json:d.z.string()}))}),n=d.z.object({error:d.z.object({message:d.z.string()})});function o(a={}){var d;let e=(0,c.withoutTrailingSlash)(null!=(d=a.baseURL)?d:"https://api.together.xyz/v1/"),f=()=>{var b;return(0,c.withUserAgentSuffix)({Authorization:`Bearer ${(0,c.loadApiKey)({apiKey:null!=(b=a.apiKey)?b:function(){if("u"<typeof process||"string"==typeof process.env.TOGETHER_API_KEY)return;let a=process.env.TOGETHER_AI_API_KEY;return"string"==typeof a&&console.warn("TOGETHER_AI_API_KEY is deprecated and will be removed in a future release. Please use TOGETHER_API_KEY instead."),a}(),environmentVariableName:"TOGETHER_API_KEY",description:"TogetherAI"})}`,...a.headers},"ai-sdk/togetherai/3.0.56")},g=b=>({provider:`togetherai.${b}`,url:({path:a})=>`${e}${a}`,headers:f,fetch:a.fetch}),h=a=>new b.OpenAICompatibleChatLanguageModel(a,{...g("chat"),includeUsage:!0,supportsStructuredOutputs:"deepseek-ai/DeepSeek-V4-Flash-0731"===a}),j=a=>new b.OpenAICompatibleEmbeddingModel(a,g("embedding")),k=a=>new l(a,{...g("image"),baseURL:null!=e?e:"https://api.together.xyz/v1/"}),m=a=>new i(a,{...g("reranking"),baseURL:null!=e?e:"https://api.together.xyz/v1/"}),n=a=>h(a);return n.specificationVersion="v4",n.completionModel=a=>new b.OpenAICompatibleCompletionLanguageModel(a,{...g("completion"),includeUsage:!0}),n.languageModel=h,n.chatModel=h,n.embeddingModel=j,n.textEmbeddingModel=j,n.image=k,n.imageModel=k,n.reranking=m,n.rerankingModel=m,n}o(),a.s(["createTogetherAI",0,o])},655819,a=>{"use strict";var b=a.i(652685),c=a.i(527990),d=a.i(912735),e=a.i(53112),f=e.z.object({error:e.z.object({message:e.z.string(),type:e.z.string().nullish(),param:e.z.any().nullish(),code:e.z.union([e.z.string(),e.z.number()]).nullish()})}),g=e.z.object({code:e.z.string(),error:e.z.string()}),h=e.z.object({error:e.z.string()}),i=e.z.union([f,g,h]),j=(0,c.createJsonErrorResponseHandler)({errorSchema:i,errorToMessage:a=>"string"==typeof a.error?"code"in a?`${a.code}: ${a.error}`:a.error:a.error.message}),k=e.z.object({aspect_ratio:e.z.string().optional(),output_format:e.z.string().optional(),sync_mode:e.z.boolean().optional(),resolution:e.z.enum(["1k","2k"]).optional(),quality:e.z.enum(["low","medium","high"]).optional(),user:e.z.string().optional()}),l=class a{constructor(a,b){this.modelId=a,this.config=b,this.specificationVersion="v4",this.maxImagesPerCall=3}get provider(){return this.config.provider}static[d.WORKFLOW_SERIALIZE](a){return(0,c.serializeModelOptions)({modelId:a.modelId,config:a.config})}static[d.WORKFLOW_DESERIALIZE](b){return new a(b.modelId,b.config)}async doGenerate({prompt:a,n:b,size:d,aspectRatio:e,seed:f,providerOptions:g,headers:h,abortSignal:i,files:l,mask:n}){var o,p,q,r,s,t,u;let v=[];null!=d&&v.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),null!=f&&v.push({type:"unsupported",feature:"seed"}),null!=n&&v.push({type:"unsupported",feature:"mask"});let w=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:g,schema:k}),x=null!=l&&l.length>0,y=x?l.map(a=>(0,c.convertImageModelFileToDataUri)(a)):[],z={model:this.modelId,prompt:a,n:b,response_format:"b64_json"};null!=e&&(z.aspect_ratio=e),(null==w?void 0:w.output_format)!=null&&(z.output_format=w.output_format),(null==w?void 0:w.sync_mode)!=null&&(z.sync_mode=w.sync_mode),(null==w?void 0:w.aspect_ratio)!=null&&null==e&&(z.aspect_ratio=w.aspect_ratio),(null==w?void 0:w.resolution)!=null&&(z.resolution=w.resolution),(null==w?void 0:w.quality)!=null&&(z.quality=w.quality),(null==w?void 0:w.user)!=null&&(z.user=w.user),1===y.length?z.image={url:y[0],type:"image_url"}:y.length>1&&(z.images=y.map(a=>({url:a,type:"image_url"})));let A=null!=(o=this.config.baseURL)?o:"https://api.x.ai/v1",B=null!=(r=null==(q=null==(p=this.config._internal)?void 0:p.currentDate)?void 0:q.call(p))?r:new Date,{value:C,responseHeaders:D}=await (0,c.postJsonToApi)({url:`${A}${x?"/images/edits":"/images/generations"}`,headers:(0,c.combineHeaders)(null==(t=(s=this.config).headers)?void 0:t.call(s),h),body:z,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(m),abortSignal:i,fetch:this.config.fetch});if(C.data.some(a=>!1===a.respect_moderation))throw Error("Image generation was blocked due to a content policy violation.");return{images:C.data.every(a=>null!=a.b64_json)?C.data.map(a=>a.b64_json):await Promise.all(C.data.map(a=>this.downloadImage(a.url,i))),warnings:v,response:{timestamp:B,modelId:this.modelId,headers:D},providerMetadata:{xai:{images:C.data.map(a=>({...a.revised_prompt?{revisedPrompt:a.revised_prompt}:{}})),...(null==(u=C.usage)?void 0:u.cost_in_usd_ticks)!=null?{costInUsdTicks:C.usage.cost_in_usd_ticks}:{}}}}}async downloadImage(a,b){let{value:d}=await (0,c.getFromApi)({url:a,validateUrl:!0,trustedOrigin:this.config.baseURL,abortSignal:b,failedResponseHandler:(0,c.createStatusCodeErrorResponseHandler)(),successfulResponseHandler:(0,c.createBinaryResponseHandler)(),fetch:this.config.fetch});return d}},m=e.z.object({data:e.z.array(e.z.object({url:e.z.string().nullish(),b64_json:e.z.string().nullish(),revised_prompt:e.z.string().nullish(),respect_moderation:e.z.boolean().nullish()})),usage:e.z.object({cost_in_usd_ticks:e.z.number().nullish()}).nullish()});function n({id:a,model:b,created:d,created_at:e}){return(0,c.createLanguageModelResponseMetadata)({id:a,model:b,created:null!=d?d:e})}var o=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({id:e.z.string(),object:e.z.string().nullish(),bytes:e.z.number().nullish(),created_at:e.z.number().nullish(),expires_at:e.z.number().nullish(),filename:e.z.string().nullish(),purpose:e.z.string().nullish(),status:e.z.string().nullish()}))),p=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({id:e.z.string(),object:e.z.string().nullish(),deleted:e.z.boolean()}))),q=/^grok-4\.20(-\d{4})?-(non-)?reasoning$/,r=e.z.object({imageDetail:e.z.enum(["low","high","auto"]).optional()});async function s({prompt:a}){var d,e,f,g,h,i,j,k,l;let m=[],n=[];for(let o of a)switch(o.role){case"system":m.push({role:"system",content:o.content});break;case"user":{let a=[];for(let d of o.content)switch(d.type){case"text":a.push({type:"input_text",text:d.text});break;case"file":switch(d.data.type){case"reference":a.push({type:"input_file",file_id:(0,c.resolveProviderReference)({reference:d.data.reference,provider:"xai"})});break;case"text":throw new b.UnsupportedFunctionalityError({functionality:"text file parts"});case"url":case"data":if("image"===(0,c.getTopLevelMediaType)(d.mediaType)){let b="url"===d.data.type?d.data.url.toString():`data:${(0,c.resolveFullMediaType)({part:d})};base64,${(0,c.convertToBase64)(d.data.data)}`,e=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:d.providerOptions,schema:r});a.push({type:"input_image",image_url:b,...(null==e?void 0:e.imageDetail)!=null&&{detail:e.imageDetail}})}else if("url"===d.data.type)a.push({type:"input_file",file_url:d.data.url.toString()});else throw new b.UnsupportedFunctionalityError({functionality:`file part media type ${d.mediaType} as inline data (xAI Responses requires a URL or a Files API reference for non-image files)`})}break;default:n.push({type:"other",message:"xAI Responses API does not support this content type in user messages"})}m.push({role:"user",content:a});break}case"assistant":for(let a of o.content)switch(a.type){case"text":{let b="string"==typeof(null==(e=null==(d=a.providerOptions)?void 0:d.xai)?void 0:e.itemId)?a.providerOptions.xai.itemId:void 0;m.push({role:"assistant",content:a.text,id:b});break}case"tool-call":{if(a.providerExecuted)break;let b="string"==typeof(null==(g=null==(f=a.providerOptions)?void 0:f.xai)?void 0:g.itemId)?a.providerOptions.xai.itemId:void 0;m.push({type:"function_call",id:null!=b?b:a.toolCallId,call_id:a.toolCallId,name:a.toolName,arguments:JSON.stringify(a.input),status:"completed"});break}case"tool-result":break;case"reasoning":{let b="string"==typeof(null==(i=null==(h=a.providerOptions)?void 0:h.xai)?void 0:i.itemId)?a.providerOptions.xai.itemId:void 0,c="string"==typeof(null==(k=null==(j=a.providerOptions)?void 0:j.xai)?void 0:k.reasoningEncryptedContent)?a.providerOptions.xai.reasoningEncryptedContent:void 0;if(null!=b||null!=c){let d=[];a.text.length>0&&d.push({type:"summary_text",text:a.text}),m.push({type:"reasoning",id:null!=b?b:"",summary:d,status:"completed",...null!=c&&{encrypted_content:c}})}else n.push({type:"other",message:"Reasoning parts without itemId or encrypted content cannot be sent back to xAI. Skipping."});break}case"reasoning-file":case"custom":case"file":n.push({type:"other",message:`xAI Responses API does not support ${a.type} in assistant messages`});break;default:n.push({type:"other",message:"xAI Responses API does not support this content type in assistant messages"})}break;case"tool":for(let a of o.content){let b;if("tool-approval-response"===a.type)continue;let d=a.output;switch(d.type){case"text":case"error-text":b=d.value;break;case"execution-denied":b=null!=(l=d.reason)?l:"tool execution denied";break;case"json":case"error-json":b=JSON.stringify(d.value);break;case"content":for(let a of(b=[],d.value))switch(a.type){case"text":b.push({type:"input_text",text:a.text});break;case"file":"image"===(0,c.getTopLevelMediaType)(a.mediaType)&&("data"===a.data.type||"url"===a.data.type)&&b.push({type:"input_image",image_url:"url"===a.data.type?a.data.url.toString():`data:${(0,c.resolveFullMediaType)({part:a})};base64,${(0,c.convertToBase64)(a.data.data)}`})}break;default:b=""}m.push({type:"function_call_output",call_id:a.toolCallId,output:b})}break;default:n.push({type:"other",message:"unsupported message role"})}return{input:m,inputWarnings:n}}function t(a){var b,c,d,e;let f=null!=(c=null==(b=a.input_tokens_details)?void 0:b.cached_tokens)?c:0,g=null!=(e=null==(d=a.output_tokens_details)?void 0:d.reasoning_tokens)?e:0,h=f<=a.input_tokens;return{inputTokens:{total:h?a.input_tokens:a.input_tokens+f,noCache:h?a.input_tokens-f:a.input_tokens,cacheRead:f,cacheWrite:void 0},outputTokens:{total:a.output_tokens,text:a.output_tokens-g,reasoning:g},raw:a}}function u(a){switch(a){case"stop":case"completed":return"stop";case"length":case"max_output_tokens":return"length";case"tool_calls":case"function_call":return"tool-calls";case"content_filter":return"content-filter";default:return"other"}}var v=e.z.union([e.z.object({type:e.z.literal("url_citation"),url:e.z.string(),title:e.z.string().optional()}),e.z.object({type:e.z.string()})]),w=e.z.object({type:e.z.string(),text:e.z.string().optional(),logprobs:e.z.array(e.z.any()).optional(),annotations:e.z.array(v).optional()}),x=e.z.object({type:e.z.string(),text:e.z.string()}),y=e.z.object({name:e.z.string().optional(),arguments:e.z.string().optional(),input:e.z.string().optional(),call_id:e.z.string().optional(),id:e.z.string(),status:e.z.string(),action:e.z.any().optional()}),z=e.z.object({type:e.z.literal("url"),url:e.z.string()}),A=e.z.discriminatedUnion("type",[e.z.object({type:e.z.literal("search"),query:e.z.string().nullish(),queries:e.z.array(e.z.string()).nullish(),sources:e.z.array(e.z.unknown()).nullish()}),e.z.object({type:e.z.literal("open_page"),url:e.z.string().nullish(),sources:e.z.array(e.z.unknown()).nullish()}),e.z.object({type:e.z.literal("find_in_page"),url:e.z.string().nullish(),pattern:e.z.string().nullish(),sources:e.z.array(e.z.unknown()).nullish()})]),B=e.z.object({name:e.z.string().optional(),arguments:e.z.string().optional(),output:e.z.string().optional(),error:e.z.string().optional(),id:e.z.string(),status:e.z.string(),server_label:e.z.string().optional()}),C=e.z.discriminatedUnion("type",[e.z.object({type:e.z.literal("web_search_call"),...y.shape}),e.z.object({type:e.z.literal("x_search_call"),...y.shape}),e.z.object({type:e.z.literal("code_interpreter_call"),...y.shape}),e.z.object({type:e.z.literal("code_execution_call"),...y.shape}),e.z.object({type:e.z.literal("view_image_call"),...y.shape}),e.z.object({type:e.z.literal("view_x_video_call"),...y.shape}),e.z.object({type:e.z.literal("file_search_call"),id:e.z.string(),status:e.z.string(),queries:e.z.array(e.z.string()).optional(),results:e.z.array(e.z.object({file_id:e.z.string(),filename:e.z.string(),score:e.z.number(),text:e.z.string()})).nullish()}),e.z.object({type:e.z.literal("image_generation_call"),id:e.z.string(),status:e.z.string(),prompt:e.z.string().nullish(),result:e.z.string().nullish()}),e.z.object({type:e.z.literal("custom_tool_call"),...y.shape}),e.z.object({type:e.z.literal("mcp_call"),...B.shape}),e.z.object({type:e.z.literal("message"),role:e.z.string(),content:e.z.array(w),id:e.z.string(),status:e.z.string()}),e.z.object({type:e.z.literal("function_call"),name:e.z.string(),arguments:e.z.string(),call_id:e.z.string(),id:e.z.string()}),e.z.object({type:e.z.literal("reasoning"),id:e.z.string(),summary:e.z.array(x),content:e.z.array(e.z.object({type:e.z.string(),text:e.z.string()})).nullish(),status:e.z.string(),encrypted_content:e.z.string().nullish()})]),D=e.z.object({input_tokens:e.z.number(),output_tokens:e.z.number(),total_tokens:e.z.number().optional(),input_tokens_details:e.z.object({cached_tokens:e.z.number().optional()}).catchall(e.z.json()).optional(),output_tokens_details:e.z.object({reasoning_tokens:e.z.number().optional()}).catchall(e.z.json()).optional(),num_sources_used:e.z.number().optional(),num_server_side_tools_used:e.z.number().optional(),cost_in_usd_ticks:e.z.number().nullish()}).catchall(e.z.json()),E=e.z.object({id:e.z.string().nullish(),created_at:e.z.number().nullish(),model:e.z.string().nullish(),object:e.z.literal("response"),output:e.z.array(C),usage:D.nullish(),status:e.z.string(),service_tier:e.z.string().nullish()}),F=e.z.union([e.z.object({type:e.z.literal("response.created"),response:E.partial({usage:!0,status:!0})}),e.z.object({type:e.z.literal("response.in_progress"),response:E.partial({usage:!0,status:!0})}),e.z.object({type:e.z.literal("response.output_item.added"),item:C,output_index:e.z.number()}),e.z.object({type:e.z.literal("response.output_item.done"),item:C,output_index:e.z.number()}),e.z.object({type:e.z.literal("response.content_part.added"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),part:w}),e.z.object({type:e.z.literal("response.content_part.done"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),part:w}),e.z.object({type:e.z.literal("response.output_text.delta"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),delta:e.z.string(),logprobs:e.z.array(e.z.any()).optional()}),e.z.object({type:e.z.literal("response.output_text.done"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),text:e.z.string(),logprobs:e.z.array(e.z.any()).optional(),annotations:e.z.array(v).optional()}),e.z.object({type:e.z.literal("response.output_text.annotation.added"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),annotation_index:e.z.number(),annotation:v}),e.z.object({type:e.z.literal("response.reasoning_summary_part.added"),item_id:e.z.string(),output_index:e.z.number(),summary_index:e.z.number(),part:x}),e.z.object({type:e.z.literal("response.reasoning_summary_part.done"),item_id:e.z.string(),output_index:e.z.number(),summary_index:e.z.number(),part:x}),e.z.object({type:e.z.literal("response.reasoning_summary_text.delta"),item_id:e.z.string(),output_index:e.z.number(),summary_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.reasoning_summary_text.done"),item_id:e.z.string(),output_index:e.z.number(),summary_index:e.z.number(),text:e.z.string()}),e.z.object({type:e.z.literal("response.reasoning_text.delta"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.reasoning_text.done"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),text:e.z.string()}),e.z.object({type:e.z.literal("response.web_search_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.web_search_call.searching"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.web_search_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.x_search_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.x_search_call.searching"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.x_search_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.file_search_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.file_search_call.searching"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.file_search_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.image_generation_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.image_generation_call.generating"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.image_generation_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_execution_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_execution_call.executing"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_execution_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_interpreter_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_interpreter_call.executing"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_interpreter_call.interpreting"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_interpreter_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_interpreter_call_code.delta"),item_id:e.z.string(),output_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.code_interpreter_call_code.done"),item_id:e.z.string(),output_index:e.z.number(),code:e.z.string()}),e.z.object({type:e.z.literal("response.custom_tool_call_input.delta"),item_id:e.z.string(),output_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.custom_tool_call_input.done"),item_id:e.z.string(),output_index:e.z.number(),input:e.z.string()}),e.z.object({type:e.z.literal("response.function_call_arguments.delta"),item_id:e.z.string(),output_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.function_call_arguments.done"),item_id:e.z.string(),output_index:e.z.number(),arguments:e.z.string()}),e.z.object({type:e.z.literal("response.mcp_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.mcp_call.executing"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.mcp_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.mcp_call.failed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.mcp_call_arguments.delta"),item_id:e.z.string(),output_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.mcp_call_arguments.done"),item_id:e.z.string(),output_index:e.z.number(),arguments:e.z.string().optional()}),e.z.object({type:e.z.literal("response.mcp_call_output.delta"),item_id:e.z.string(),output_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.mcp_call_output.done"),item_id:e.z.string(),output_index:e.z.number(),output:e.z.string().optional()}),e.z.object({type:e.z.literal("response.incomplete"),response:e.z.object({incomplete_details:e.z.object({reason:e.z.string()}).nullish(),usage:D.nullish(),service_tier:e.z.string().nullish()})}),e.z.object({type:e.z.literal("response.failed"),response:e.z.object({error:e.z.object({code:e.z.string().nullish(),message:e.z.string()}).nullish(),incomplete_details:e.z.object({reason:e.z.string()}).nullish(),usage:D.nullish()})}),e.z.object({type:e.z.literal("error"),code:e.z.string().nullish(),message:e.z.string(),param:e.z.string().nullish()}),e.z.object({type:e.z.literal("response.done"),response:E}),e.z.object({type:e.z.literal("response.completed"),response:E})]),G=e.z.object({reasoningEffort:e.z.enum(["none","low","medium","high","xhigh"]).optional(),reasoningSummary:e.z.enum(["auto","concise","detailed"]).optional(),logprobs:e.z.boolean().optional(),topLogprobs:e.z.number().int().min(0).max(8).optional(),serviceTier:e.z.enum(["default","priority"]).optional(),store:e.z.boolean().optional(),previousResponseId:e.z.string().optional(),include:e.z.array(e.z.enum(["file_search_call.results"])).nullish()}),H=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({vectorStoreIds:e.z.array(e.z.string()),maxNumResults:e.z.number().optional()}))),I=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({queries:e.z.array(e.z.string()),results:e.z.array(e.z.object({fileId:e.z.string(),filename:e.z.string(),score:e.z.number().min(0).max(1),text:e.z.string()})).nullable()}))),J=(0,c.createProviderExecutedToolFactory)({id:"xai.file_search",inputSchema:(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({}))),outputSchema:I}),K=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({action:e.z.enum(["auto","generate","edit"]).optional()}))),L=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({}))),M=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({result:e.z.string(),prompt:e.z.string().optional()}))),N=(0,c.createProviderExecutedToolFactory)({id:"xai.image_generation",inputSchema:L,outputSchema:M}),O=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({serverUrl:e.z.string().describe("The URL of the MCP server"),serverLabel:e.z.string().optional().describe("A label for the MCP server"),serverDescription:e.z.string().optional().describe("Description of the MCP server"),allowedTools:e.z.array(e.z.string()).optional().describe("List of allowed tool names"),headers:e.z.record(e.z.string(),e.z.string()).optional().describe("Custom headers to send"),authorization:e.z.string().optional().describe("Authorization header value")}))),P=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({name:e.z.string(),arguments:e.z.string(),result:e.z.unknown()}))),Q=(0,c.createProviderExecutedToolFactory)({id:"xai.mcp",inputSchema:(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({}))),outputSchema:P}),R=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({allowedDomains:e.z.array(e.z.string()).max(5).optional(),excludedDomains:e.z.array(e.z.string()).max(5).optional(),enableImageSearch:e.z.boolean().optional(),enableImageUnderstanding:e.z.boolean().optional()}))),S=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({action:e.z.discriminatedUnion("type",[e.z.object({type:e.z.literal("search"),query:e.z.string().optional(),queries:e.z.array(e.z.string()).optional()}),e.z.object({type:e.z.literal("openPage"),url:e.z.string().nullish()}),e.z.object({type:e.z.literal("findInPage"),url:e.z.string().nullish(),pattern:e.z.string().nullish()})]).optional(),sources:e.z.array(e.z.object({type:e.z.literal("url"),url:e.z.string()})).optional()}))),T=(0,c.createProviderExecutedToolFactory)({id:"xai.web_search",inputSchema:(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({}))),outputSchema:S}),U=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({allowedXHandles:e.z.array(e.z.string()).max(10).optional(),excludedXHandles:e.z.array(e.z.string()).max(10).optional(),fromDate:e.z.string().optional(),toDate:e.z.string().optional(),enableImageUnderstanding:e.z.boolean().optional(),enableVideoUnderstanding:e.z.boolean().optional()}))),V=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({query:e.z.string(),posts:e.z.array(e.z.object({author:e.z.string(),text:e.z.string(),url:e.z.string(),likes:e.z.number()}))}))),W=(0,c.createProviderExecutedToolFactory)({id:"xai.x_search",inputSchema:(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({}))),outputSchema:V});async function X({tools:a,toolChoice:d}){let e=(null==a?void 0:a.length)?a:void 0,f=[];if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:f};let g=[],h=new Map;for(let a of e)if(h.set(a.name,a),"provider"===a.type)switch(a.id){case"xai.web_search":{let b=await (0,c.validateTypes)({value:a.args,schema:R});g.push({type:"web_search",allowed_domains:b.allowedDomains,excluded_domains:b.excludedDomains,enable_image_search:b.enableImageSearch,enable_image_understanding:b.enableImageUnderstanding});break}case"xai.x_search":{let b=await (0,c.validateTypes)({value:a.args,schema:U});g.push({type:"x_search",allowed_x_handles:b.allowedXHandles,excluded_x_handles:b.excludedXHandles,from_date:b.fromDate,to_date:b.toDate,enable_image_understanding:b.enableImageUnderstanding,enable_video_understanding:b.enableVideoUnderstanding});break}case"xai.code_execution":g.push({type:"code_interpreter"});break;case"xai.view_image":g.push({type:"view_image"});break;case"xai.view_x_video":g.push({type:"view_x_video"});break;case"xai.image_generation":{let b=await (0,c.validateTypes)({value:a.args,schema:K});g.push({type:"image_generation",action:b.action});break}case"xai.file_search":{let b=await (0,c.validateTypes)({value:a.args,schema:H});g.push({type:"file_search",vector_store_ids:b.vectorStoreIds,max_num_results:b.maxNumResults});break}case"xai.mcp":{let b=await (0,c.validateTypes)({value:a.args,schema:O});g.push({type:"mcp",server_url:b.serverUrl,server_label:b.serverLabel,server_description:b.serverDescription,allowed_tools:b.allowedTools,headers:b.headers,authorization:b.authorization});break}default:f.push({type:"unsupported",feature:`provider-defined tool ${a.name}`})}else g.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,...null!=a.strict?{strict:a.strict}:{}});if(null==d)return{tools:g,toolChoice:void 0,toolWarnings:f};let i=d.type;switch(i){case"auto":case"none":return{tools:g,toolChoice:i,toolWarnings:f};case"required":return{tools:g,toolChoice:"required",toolWarnings:f};case"tool":{let a=h.get(d.toolName);if(null==a)return{tools:g,toolChoice:void 0,toolWarnings:f};if("provider"===a.type)return f.push({type:"unsupported",feature:`toolChoice for server-side tool "${a.name}"`}),{tools:g,toolChoice:void 0,toolWarnings:f};return{tools:g,toolChoice:{type:"function",name:a.name},toolWarnings:f}}default:throw new b.UnsupportedFunctionalityError({functionality:`tool choice type: ${i}`})}}function Y({message:a,code:b,eventType:d,data:e}){var f,g;let h,i="number"==typeof(h="string"==typeof(f=b)&&/^\d{3}$/.test(f)?Number(f):f)&&Number.isInteger(h)&&h>=400&&h<=599?h:void 0;return(0,c.createProviderStreamError)({message:a,type:d,code:null!=b?b:void 0,...null!=i?{statusCode:i,isRetryable:408===(g=i)||409===g||429===g||g>=500}:function(a){switch(a){case"rate_limit_exceeded":case"rate_limit_error":return{statusCode:429,isRetryable:!0};case"insufficient_quota":return{statusCode:429,isRetryable:!1};case"api_error":case"internal_server_error":case"server_error":return{statusCode:500,isRetryable:!0};case"overloaded_error":case"service_unavailable":return{statusCode:503,isRetryable:!0};case"timeout":case"timeout_error":return{statusCode:504,isRetryable:!0};case"authentication_error":case"invalid_api_key":return{statusCode:401,isRetryable:!1};case"permission_error":return{statusCode:403,isRetryable:!1};case"not_found_error":case"model_not_found":return{statusCode:404,isRetryable:!1};case"bad_request":case"context_length_exceeded":case"invalid_request_error":return{statusCode:400,isRetryable:!1};default:return{}}}(b),data:e})}var Z={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/],"text/*":[/^https?:\/\/.*$/]},$=class a{constructor(a,b){this.specificationVersion="v4",this.supportedUrls=Z,this.modelId=a,this.config=b}static[d.WORKFLOW_SERIALIZE](a){return(0,c.serializeModelOptions)({modelId:a.modelId,config:a.config})}static[d.WORKFLOW_DESERIALIZE](b){return new a(b.modelId,b.config)}get provider(){return this.config.provider}static async prepareRequest({modelId:a,options:{prompt:b,maxOutputTokens:d,temperature:e,topP:f,topK:g,frequencyPenalty:h,presencePenalty:i,stopSequences:j,seed:k,responseFormat:l,providerOptions:m,tools:n,toolChoice:o,reasoning:p}}){var r,t,u,v,w,x,y,z,A;let B=[],C=null!=(r=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:m,schema:G}))?r:{};null!=g&&B.push({type:"unsupported",feature:"topK"}),null!=h&&B.push({type:"unsupported",feature:"frequencyPenalty"}),null!=i&&B.push({type:"unsupported",feature:"presencePenalty"}),null!=j&&B.push({type:"unsupported",feature:"stopSequences"});let D=null==(t=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.web_search"===a.id))?void 0:t.name,E=null==(u=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.x_search"===a.id))?void 0:u.name,F=null==(v=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.code_execution"===a.id))?void 0:v.name,H=null==(w=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.mcp"===a.id))?void 0:w.name,I=null==(x=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.file_search"===a.id))?void 0:x.name,J=null==(y=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.image_generation"===a.id))?void 0:y.name,{input:K,inputWarnings:L}=await s({prompt:b,store:null==(z=C.store)||z});B.push(...L);let{tools:M,toolChoice:N,toolWarnings:O}=await X({tools:n,toolChoice:o});B.push(...O);let P=C.include?[...C.include]:void 0;!1===C.store&&(P=null==P?["reasoning.encrypted_content"]:[...P,"reasoning.encrypted_content"]);let Q=C.reasoningEffort;null==Q&&(0,c.isCustomReasoning)(p)&&(q.test(a)?B.push({type:"unsupported",feature:"reasoning",details:`reasoning "${p}" is not supported by this model.`}):Q="none"===p?"none":(0,c.mapReasoningToProviderEffort)({reasoning:p,effortMap:{minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"grok-4.6"===a?"xhigh":"high"},warnings:B}));let R={model:a,input:K,logprobs:!0===C.logprobs||null!=C.topLogprobs||void 0,top_logprobs:C.topLogprobs,max_output_tokens:d,temperature:e,top_p:f,seed:k,...(null==l?void 0:l.type)==="json"&&{text:{format:null!=l.schema?{type:"json_schema",strict:!0,name:null!=(A=l.name)?A:"response",description:l.description,schema:l.schema}:{type:"json_object"}}},...(null!=Q||null!=C.reasoningSummary)&&{reasoning:{...null!=Q&&{effort:Q},...null!=C.reasoningSummary&&{summary:C.reasoningSummary}}},...!1===C.store&&{store:C.store},...null!=P&&{include:P},...null!=C.previousResponseId&&{previous_response_id:C.previousResponseId},...null!=C.serviceTier&&{service_tier:C.serviceTier}};return M&&M.length>0&&(R.tools=M),null!=N&&(R.tool_choice=N),{args:R,warnings:B,webSearchToolName:D,xSearchToolName:E,codeExecutionToolName:F,mcpToolName:H,fileSearchToolName:I,imageGenerationToolName:J}}getArgs(b){return a.prepareRequest({modelId:this.modelId,options:b})}async doGenerate(a){var b,d,e,f,g,h,i,k,l,m,o,p,q,r,s,v,w,x;let{args:y,warnings:z,webSearchToolName:A,xSearchToolName:B,codeExecutionToolName:C,mcpToolName:D,fileSearchToolName:F,imageGenerationToolName:G}=await this.getArgs(a),{responseHeaders:H,value:I,rawValue:J}=await (0,c.postJsonToApi)({url:`${null!=(b=this.config.baseURL)?b:"https://api.x.ai/v1"}/responses`,headers:(0,c.combineHeaders)(null==(e=(d=this.config).headers)?void 0:e.call(d),a.headers),body:y,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(E),abortSignal:a.abortSignal,fetch:this.config.fetch}),K=[],L=!1,M=["web_search","web_search_with_snippets","browse_page"],N=["x_user_search","x_keyword_search","x_semantic_search","x_thread_fetch"];for(let a of I.output){if("file_search_call"===a.type){let b=null!=F?F:"file_search";K.push({type:"tool-call",toolCallId:a.id,toolName:b,input:"",providerExecuted:!0}),K.push({type:"tool-result",toolCallId:a.id,toolName:b,result:{queries:null!=(f=a.queries)?f:[],results:null!=(h=null==(g=a.results)?void 0:g.map(a=>({fileId:a.file_id,filename:a.filename,score:a.score,text:a.text})))?h:null}});continue}if("image_generation_call"===a.type){let b=null!=G?G:"image_generation";K.push({type:"tool-call",toolCallId:a.id,toolName:b,input:"{}",providerExecuted:!0}),null!=a.result?K.push({type:"tool-result",toolCallId:a.id,toolName:b,result:{result:a.result,...null!=a.prompt&&{prompt:a.prompt}}}):K.push({type:"tool-result",toolCallId:a.id,toolName:b,isError:!0,result:`Image generation failed (status: ${a.status}).`});continue}if("web_search_call"===a.type||"x_search_call"===a.type||"code_interpreter_call"===a.type||"code_execution_call"===a.type||"view_image_call"===a.type||"view_x_video_call"===a.type||"custom_tool_call"===a.type||"mcp_call"===a.type){let b=null!=(i=a.name)?i:"";M.includes(null!=(k=a.name)?k:"")||"web_search_call"===a.type?b=null!=A?A:"web_search":N.includes(null!=(l=a.name)?l:"")||"x_search_call"===a.type?b=null!=B?B:"x_search":"code_execution"===a.name||"code_interpreter_call"===a.type||"code_execution_call"===a.type?b=null!=C?C:"code_execution":"mcp_call"===a.type&&(b=null!=(m=null!=D?D:a.name)?m:"mcp");let c="custom_tool_call"===a.type?null!=(o=a.input)?o:"":"mcp_call"===a.type?null!=(p=a.arguments)?p:"":null!=(q=a.arguments)?q:"";K.push({type:"tool-call",toolCallId:a.id,toolName:b,input:c,providerExecuted:!0}),"web_search_call"===a.type&&K.push({type:"tool-result",toolCallId:a.id,toolName:b,result:_(a.action)});continue}switch(a.type){case"message":for(let b of a.content)if(b.text&&K.push({type:"text",text:b.text}),b.annotations)for(let a of b.annotations)"url_citation"===a.type&&"url"in a&&K.push({type:"source",sourceType:"url",id:this.config.generateId(),url:a.url,title:null!=(r=a.title)?r:a.url});break;case"function_call":L=!0,K.push({type:"tool-call",toolCallId:a.call_id,toolName:a.name,input:a.arguments});break;case"reasoning":{let b=(a.summary.length>0?a.summary.map(a=>a.text):(null!=(s=a.content)?s:[]).map(a=>a.text)).filter(a=>a&&a.length>0).join("");if(b||a.encrypted_content){let c=a.encrypted_content||a.id;K.push({type:"reasoning",text:b,...c&&{providerMetadata:{xai:{...a.encrypted_content&&{reasoningEncryptedContent:a.encrypted_content},...a.id&&{itemId:a.id}}}}})}}}}return{content:K,finishReason:{unified:L?"tool-calls":u(I.status),raw:null!=(v=I.status)?v:void 0},usage:I.usage?t(I.usage):{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...((null==(w=I.usage)?void 0:w.cost_in_usd_ticks)!=null||null!=I.service_tier)&&{providerMetadata:{xai:{...(null==(x=I.usage)?void 0:x.cost_in_usd_ticks)!=null&&{costInUsdTicks:I.usage.cost_in_usd_ticks},...null!=I.service_tier&&{serviceTier:I.service_tier}}}},request:{body:y},response:{...n(I),headers:H,body:J},warnings:z}}async doStream(a){var b,d,e;let f,g,h,{args:i,warnings:k,webSearchToolName:l,xSearchToolName:m,codeExecutionToolName:o,mcpToolName:p,fileSearchToolName:q,imageGenerationToolName:r}=await this.getArgs(a),s={...i,stream:!0},{responseHeaders:v,value:w}=await (0,c.postJsonToApi)({url:`${null!=(b=this.config.baseURL)?b:"https://api.x.ai/v1"}/responses`,headers:(0,c.combineHeaders)(null==(e=(d=this.config).headers)?void 0:e.call(d),a.headers),body:s,failedResponseHandler:j,successfulResponseHandler:(0,c.createEventSourceResponseHandler)(F),abortSignal:a.abortSignal,fetch:this.config.fetch}),x={unified:"other",raw:void 0},y=!1,z=!0,A={},B=new Set,C={},D={},E=this;return{stream:w.pipeThrough(new TransformStream({start(a){a.enqueue({type:"stream-start",warnings:k})},transform(b,c){var d,e,i,j,k,s,v,w,F,G,H,I,J,K,L,M,N;if(a.includeRawChunks&&c.enqueue({type:"raw",rawValue:b.rawValue}),!b.success)return void c.enqueue({type:"error",error:b.error});let O=b.value;if("response.created"===O.type||"response.in_progress"===O.type){z&&(c.enqueue({type:"response-metadata",...n(O.response)}),z=!1);return}if("response.reasoning_summary_part.added"===O.type){let a=`reasoning-${O.item_id}`;null==D[O.item_id]&&(D[O.item_id]={},c.enqueue({type:"reasoning-start",id:a,providerMetadata:{xai:{itemId:O.item_id}}}))}if("response.reasoning_summary_text.delta"===O.type){let a=`reasoning-${O.item_id}`;c.enqueue({type:"reasoning-delta",id:a,delta:O.delta,providerMetadata:{xai:{itemId:O.item_id}}});return}if("response.reasoning_summary_text.done"===O.type)return;if("response.reasoning_text.delta"===O.type){let a=`reasoning-${O.item_id}`;null==D[O.item_id]&&(D[O.item_id]={},c.enqueue({type:"reasoning-start",id:a,providerMetadata:{xai:{itemId:O.item_id}}})),c.enqueue({type:"reasoning-delta",id:a,delta:O.delta,providerMetadata:{xai:{itemId:O.item_id}}});return}if("response.reasoning_text.done"!==O.type){if("response.output_text.delta"===O.type){let a=`text-${O.item_id}`;null==A[a]&&(A[a]={type:"text"},c.enqueue({type:"text-start",id:a})),c.enqueue({type:"text-delta",id:a,delta:O.delta});return}if("response.output_text.done"===O.type){if(O.annotations)for(let a of O.annotations)"url_citation"===a.type&&"url"in a&&c.enqueue({type:"source",sourceType:"url",id:E.config.generateId(),url:a.url,title:null!=(d=a.title)?d:a.url});return}if("response.output_text.annotation.added"===O.type){let a=O.annotation;"url_citation"===a.type&&"url"in a&&c.enqueue({type:"source",sourceType:"url",id:E.config.generateId(),url:a.url,title:null!=(e=a.title)?e:a.url});return}if("response.done"===O.type||"response.completed"===O.type||"response.incomplete"===O.type){let a=O.response;if(a.usage&&(f=t(a.usage),g=null!=(i=a.usage.cost_in_usd_ticks)?i:void 0),h=null!=(j=a.service_tier)?j:void 0,"response.incomplete"===O.type){let b="incomplete_details"in a?null==(k=a.incomplete_details)?void 0:k.reason:void 0;x={unified:b?u(b):"other",raw:null!=b?b:"incomplete"}}else"status"in a&&a.status&&(x={unified:y?"tool-calls":u(a.status),raw:a.status});return}if("response.failed"===O.type){let a=null==(s=O.response.incomplete_details)?void 0:s.reason;x={unified:a?u(a):"error",raw:null!=a?a:"error"},O.response.usage&&(f=t(O.response.usage)),null!=O.response.error&&c.enqueue({type:"error",error:Y({message:O.response.error.message,code:O.response.error.code,eventType:O.type,data:O})});return}if("error"===O.type)return void c.enqueue({type:"error",error:Y({message:O.message,code:O.code,eventType:O.type,data:O})});if("response.custom_tool_call_input.delta"!==O.type&&"response.custom_tool_call_input.done"!==O.type){if("response.function_call_arguments.delta"===O.type){let a=C[O.output_index];null!=a&&c.enqueue({type:"tool-input-delta",id:a.toolCallId,delta:O.delta});return}if("response.function_call_arguments.done"!==O.type){if("response.image_generation_call.in_progress"===O.type||"response.image_generation_call.generating"===O.type||"response.image_generation_call.completed"===O.type){if(!B.has(O.item_id)){B.add(O.item_id);let a=null!=r?r:"image_generation";c.enqueue({type:"tool-input-start",id:O.item_id,toolName:a}),c.enqueue({type:"tool-input-delta",id:O.item_id,delta:"{}"}),c.enqueue({type:"tool-input-end",id:O.item_id}),c.enqueue({type:"tool-call",toolCallId:O.item_id,toolName:a,input:"{}",providerExecuted:!0})}return}if("response.output_item.added"===O.type||"response.output_item.done"===O.type){let a=O.item;if("reasoning"===a.type){if("response.output_item.done"===O.type){let b=`reasoning-${a.id}`;a.id in D||(D[a.id]={},c.enqueue({type:"reasoning-start",id:b,providerMetadata:{xai:{...a.id&&{itemId:a.id}}}})),c.enqueue({type:"reasoning-end",id:b,providerMetadata:{xai:{...a.encrypted_content&&{reasoningEncryptedContent:a.encrypted_content},...a.id&&{itemId:a.id}}}}),delete D[a.id]}return}if("file_search_call"===a.type){let b=null!=q?q:"file_search";B.has(a.id)||(B.add(a.id),c.enqueue({type:"tool-input-start",id:a.id,toolName:b}),c.enqueue({type:"tool-input-delta",id:a.id,delta:""}),c.enqueue({type:"tool-input-end",id:a.id}),c.enqueue({type:"tool-call",toolCallId:a.id,toolName:b,input:"",providerExecuted:!0})),"response.output_item.done"===O.type&&c.enqueue({type:"tool-result",toolCallId:a.id,toolName:b,result:{queries:null!=(v=a.queries)?v:[],results:null!=(F=null==(w=a.results)?void 0:w.map(a=>({fileId:a.file_id,filename:a.filename,score:a.score,text:a.text})))?F:null}});return}if("image_generation_call"===a.type){let b=null!=r?r:"image_generation";B.has(a.id)||(B.add(a.id),c.enqueue({type:"tool-input-start",id:a.id,toolName:b}),c.enqueue({type:"tool-input-delta",id:a.id,delta:"{}"}),c.enqueue({type:"tool-input-end",id:a.id}),c.enqueue({type:"tool-call",toolCallId:a.id,toolName:b,input:"{}",providerExecuted:!0})),"response.output_item.done"===O.type&&(null!=a.result?c.enqueue({type:"tool-result",toolCallId:a.id,toolName:b,result:{result:a.result,...null!=a.prompt&&{prompt:a.prompt}}}):c.enqueue({type:"tool-result",toolCallId:a.id,toolName:b,isError:!0,result:`Image generation failed (status: ${a.status}).`}));return}if("web_search_call"===a.type||"x_search_call"===a.type||"code_interpreter_call"===a.type||"code_execution_call"===a.type||"view_image_call"===a.type||"view_x_video_call"===a.type||"custom_tool_call"===a.type||"mcp_call"===a.type){let b=null!=(G=a.name)?G:"";["web_search","web_search_with_snippets","browse_page"].includes(null!=(H=a.name)?H:"")||"web_search_call"===a.type?b=null!=l?l:"web_search":["x_user_search","x_keyword_search","x_semantic_search","x_thread_fetch"].includes(null!=(I=a.name)?I:"")||"x_search_call"===a.type?b=null!=m?m:"x_search":"code_execution"===a.name||"code_interpreter_call"===a.type||"code_execution_call"===a.type?b=null!=o?o:"code_execution":"mcp_call"===a.type&&(b=null!=(J=null!=p?p:a.name)?J:"mcp");let d="custom_tool_call"===a.type?null!=(K=a.input)?K:"":"mcp_call"===a.type?null!=(L=a.arguments)?L:"":null!=(M=a.arguments)?M:"";("custom_tool_call"===a.type?"response.output_item.done"!==O.type:B.has(a.id))||B.has(a.id)||(B.add(a.id),c.enqueue({type:"tool-input-start",id:a.id,toolName:b}),c.enqueue({type:"tool-input-delta",id:a.id,delta:d}),c.enqueue({type:"tool-input-end",id:a.id}),c.enqueue({type:"tool-call",toolCallId:a.id,toolName:b,input:d,providerExecuted:!0})),"response.output_item.done"===O.type&&c.enqueue({type:"tool-result",toolCallId:a.id,toolName:b,result:"web_search_call"===a.type?_(a.action):{}});return}if("message"===a.type)for(let b of a.content){if(b.text&&b.text.length>0){let d=`text-${a.id}`;null==A[d]&&(A[d]={type:"text"},c.enqueue({type:"text-start",id:d}),c.enqueue({type:"text-delta",id:d,delta:b.text}))}if(b.annotations)for(let a of b.annotations)"url_citation"===a.type&&"url"in a&&c.enqueue({type:"source",sourceType:"url",id:E.config.generateId(),url:a.url,title:null!=(N=a.title)?N:a.url})}else"function_call"===a.type&&("response.output_item.added"===O.type?(C[O.output_index]={toolName:a.name,toolCallId:a.call_id},c.enqueue({type:"tool-input-start",id:a.call_id,toolName:a.name})):"response.output_item.done"===O.type&&(y=!0,C[O.output_index]=void 0,c.enqueue({type:"tool-input-end",id:a.call_id}),c.enqueue({type:"tool-call",toolCallId:a.call_id,toolName:a.name,input:a.arguments})))}}}}},flush(a){for(let[b,c]of Object.entries(A))"text"===c.type&&a.enqueue({type:"text-end",id:b});a.enqueue({type:"finish",finishReason:x,usage:null!=f?f:{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...(null!=g||null!=h)&&{providerMetadata:{xai:{...null!=g&&{costInUsdTicks:g},...null!=h&&{serviceTier:h}}}}})}})),request:{body:s},response:{headers:v}}}};function _(a){var b;let c=A.safeParse(a);if(!c.success)return{};let d=c.data,e=null==(b=d.sources)?void 0:b.flatMap(a=>{let b=z.safeParse(a);return b.success?[b.data]:[]}),f=null!=e&&e.length>0?{sources:e}:{};switch(d.type){case"search":return{action:{type:"search",...null!=d.query&&{query:d.query},...null!=d.queries&&{queries:d.queries}},...f};case"open_page":return{action:{type:"openPage",url:d.url},...f};case"find_in_page":return{action:{type:"findInPage",url:d.url,pattern:d.pattern},...f}}}var aa=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({inputFileExpiresAfter:e.z.number().int().min(3600).max(2592e3).optional()}))),ab=e.z.object({data:e.z.array(e.z.object({url:e.z.string().nullish(),b64_json:e.z.string().nullish(),revised_prompt:e.z.string().nullish(),respect_moderation:e.z.boolean().nullish()})),usage:e.z.object({cost_in_usd_ticks:e.z.number().nullish()}).nullish()}),ac=()=>e.z.object({batch_id:e.z.string(),name:e.z.string().nullish(),create_time:e.z.string().nullish(),expire_time:e.z.string().nullish(),cancel_time:e.z.string().nullish(),cancel_by_xai_message:e.z.string().nullish(),state:e.z.object({num_requests:e.z.number().nullish(),num_pending:e.z.number().nullish(),num_success:e.z.number().nullish(),num_error:e.z.number().nullish(),num_cancelled:e.z.number().nullish()}).nullish()}),ad=(0,c.lazySchema)(()=>(0,c.zodSchema)(ac())),ae=e.z.object({code:e.z.union([e.z.string(),e.z.number()]).nullish(),message:e.z.string().nullish()}),af=e.z.object({batch_request_id:e.z.string(),batch_result:e.z.object({response:e.z.object({chat_get_completion:e.z.unknown().nullish(),image_generation:e.z.unknown().nullish()}).nullish(),error:ae.nullish()}).nullish(),error_message:e.z.string().nullish()}),ag=e.z.object({id:e.z.string().nullish(),created:e.z.number().nullish(),model:e.z.string().nullish(),choices:e.z.array(e.z.object({message:e.z.object({role:e.z.enum(["assistant","tool"]),content:e.z.string().nullish(),reasoning_content:e.z.string().nullish(),tool_calls:e.z.array(e.z.object({id:e.z.string(),type:e.z.literal("function"),function:e.z.object({name:e.z.string(),arguments:e.z.string()})})).nullish()}),index:e.z.number(),finish_reason:e.z.string().nullish()})).nullish(),usage:e.z.object({prompt_tokens:e.z.number(),completion_tokens:e.z.number(),total_tokens:e.z.number(),cost_in_usd_ticks:e.z.number().nullish(),prompt_tokens_details:e.z.object({cached_tokens:e.z.number().nullish()}).nullish(),completion_tokens_details:e.z.object({reasoning_tokens:e.z.number().nullish()}).nullish()}).nullish(),citations:e.z.array(e.z.string().url()).nullish(),service_tier:e.z.string().nullish(),code:e.z.string().nullish(),error:e.z.string().nullish()}),ah=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({results:e.z.array(af),pagination_token:e.z.string().nullish()}))),ai=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({batches:e.z.array(ac()),pagination_token:e.z.string().nullish()}))),aj=class{constructor(a){this.options=a,this.specificationVersion="v4",this.supportedUrls=Z,this.provider=a.provider}async doStartBatch(a){var d,e;for(let c of a.requests){let a=c.type;if("text"!==a&&"image"!==a)throw new b.UnsupportedFunctionalityError({functionality:`batch request type: ${a}`,message:`The xAI Batch API does not support batch requests with type "${a}".`})}let f=[],g=null==a.webhookUrl?[]:[{warning:{type:"unsupported",feature:"webhookUrl",details:"The xAI Batch API does not support per-batch webhook URLs."}}],h=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:a.providerOptions,schema:aa});for(let b of a.requests){let a=await this.prepareRequest(b);for(let c of(f.push(JSON.stringify({custom_id:b.id,method:"POST",url:a.endpoint,body:a.body}),"\n"),a.warnings))g.push({requestId:b.id,warning:c})}let i=new Blob(f,{type:"application/jsonl"});f.length=0;let k=new FormData;(null==h?void 0:h.inputFileExpiresAfter)!=null&&k.append("expires_after",String(h.inputFileExpiresAfter)),k.append("file",i,"batch.jsonl");let l=(0,c.combineHeaders)(null==(e=(d=this.options.config).headers)?void 0:e.call(d),a.headers),{value:m}=await (0,c.postFormDataToApi)({url:this.getUrl("/files"),headers:l,formData:k,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(o),abortSignal:a.abortSignal,fetch:this.options.config.fetch}),{value:n}=await (0,c.postJsonToApi)({url:this.getUrl("/batches"),headers:l,body:{name:"ai-sdk-text-batch",input_file_id:m.id},failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(ad),abortSignal:a.abortSignal,fetch:this.options.config.fetch});return{batchId:n.batch_id,...ak(n),providerMetadata:{xai:{inputFileId:m.id,...null!=m.expires_at?{inputFileExpiresAt:new Date(1e3*m.expires_at).toISOString()}:{}}},warnings:g}}async doGetBatchStatus(a){return ak(await this.retrieveBatch(a))}async doCancelBatch(a){var b,d;return await (0,c.postJsonToApi)({url:this.getUrl(`/batches/${encodeURIComponent(a.batchId)}:cancel`),headers:(0,c.combineHeaders)(null==(d=(b=this.options.config).headers)?void 0:d.call(b),a.headers),body:{},failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(ad),abortSignal:a.abortSignal,fetch:this.options.config.fetch}),{}}async doListBatches(a){var b,d;let e=new URL(this.getUrl("/batches"));null!=a.limit&&e.searchParams.set("limit",String(a.limit)),null!=a.cursor&&e.searchParams.set("pagination_token",a.cursor);let{value:f}=await (0,c.getFromApi)({url:e.toString(),headers:(0,c.combineHeaders)(null==(d=(b=this.options.config).headers)?void 0:d.call(b),a.headers),failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(ai),abortSignal:a.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return{batches:f.batches.map(a=>({batchId:a.batch_id,...ak(a)})),...null!=f.pagination_token?{nextCursor:f.pagination_token}:{}}}async doGetBatchResults(a){if("pending"===ak(await this.retrieveBatch(a)).status)throw new b.InvalidArgumentError({argument:"batchId",message:`xAI batch "${a.batchId}" is not complete.`});return(0,c.convertAsyncIteratorToReadableStream)(this.iterateBatchResults(a))}async retrieveBatch(a){var b,d;let{value:e}=await (0,c.getFromApi)({url:this.getUrl(`/batches/${encodeURIComponent(a.batchId)}`),headers:(0,c.combineHeaders)(null==(d=(b=this.options.config).headers)?void 0:d.call(b),a.headers),failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(ad),abortSignal:a.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return e}async *iterateBatchResults(a){var b,d,e;let f;do{let g=new URLSearchParams({limit:String(1e3)});null!=f&&g.set("pagination_token",f);let{value:h}=await (0,c.getFromApi)({url:this.getUrl(`/batches/${encodeURIComponent(a.batchId)}/results?${g}`),headers:(0,c.combineHeaders)(null==(d=(b=this.options.config).headers)?void 0:d.call(b),a.headers),failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(ah),abortSignal:a.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});for(let b of h.results)yield await this.convertBatchResult(b,a.abortSignal);f=null!=(e=h.pagination_token)?e:void 0}while(null!=f)}async convertBatchResult(a,b){var d,e,f,g,h,i,j,k,l;let m=null==(d=a.batch_result)?void 0:d.error;if((null!=(f=null==(e=a.error_message)?void 0:e.length)?f:0)>0||(null==m?void 0:m.code)!=null&&0!==m.code&&"0"!==m.code||(null==m?void 0:m.code)==null&&(null!=(h=null==(g=null==m?void 0:m.message)?void 0:g.length)?h:0)>0){let b,c,d=(b=null==(k=(j=a).batch_result)?void 0:k.error,{message:j.error_message||(null==b?void 0:b.message)||"xAI batch request failed.",...(null==b?void 0:b.code)!=null&&0!==b.code&&"0"!==b.code?{code:String(b.code)}:{}});return{type:"text",id:a.batch_request_id,status:(c=String(l=null==m?void 0:m.code).toLowerCase(),1===l||"1"===c||"cancelled"===c||"batch_cancelled"===c)?"cancelled":"failed",error:d}}let o=null==(i=a.batch_result)?void 0:i.response;if((null==o?void 0:o.chat_get_completion)!=null){let b=await (0,c.safeValidateTypes)({value:o.chat_get_completion,schema:(0,c.zodSchema)(ag)});if(!b.success)return al(a.batch_request_id);let d=function(a){var b,d,e,f,g,h,i,j,k,l,m;let o,p,q,r;if(null!=a.error)return{success:!1,error:{message:a.error,...null!=a.code?{code:a.code}:{}}};let s=a.choices;if(null==s||0===s.length)return{success:!1,error:{message:"xAI returned a batch response without any choices.",code:"invalid_response"}};let t=[],u=new Set(s.filter(a=>"tool"===a.message.role).flatMap(a=>{var b;return(null!=(b=a.message.tool_calls)?b:[]).map(a=>a.id)}));for(let a of s){if("tool"===a.message.role){if(null!=a.message.content)for(let c of null!=(b=a.message.tool_calls)?b:[])t.push({type:"tool-result",toolCallId:c.id,toolName:c.function.name,result:a.message.content,dynamic:!0});continue}for(let b of(o=a,a.message.content&&t.push({type:"text",text:a.message.content}),a.message.reasoning_content&&t.push({type:"reasoning",text:a.message.reasoning_content}),null!=(d=a.message.tool_calls)?d:[]))t.push({type:"tool-call",toolCallId:b.id,toolName:b.function.name,input:b.function.arguments,...u.has(b.id)?{providerExecuted:!0,dynamic:!0}:{}})}for(let b of null!=(e=a.citations)?e:[])t.push({type:"source",sourceType:"url",id:b,url:b});return{success:!0,result:{content:t,finishReason:{unified:function(a){switch(a){case"stop":return"stop";case"length":return"length";case"tool_calls":case"function_call":return"tool-calls";case"content_filter":return"content-filter";default:return"other"}}(null==o?void 0:o.finish_reason),raw:null!=(f=null==o?void 0:o.finish_reason)?f:void 0},usage:a.usage?(p=null!=(k=null==(j=(i=a.usage).prompt_tokens_details)?void 0:j.cached_tokens)?k:0,q=null!=(m=null==(l=i.completion_tokens_details)?void 0:l.reasoning_tokens)?m:0,{inputTokens:{total:(r=p<=i.prompt_tokens)?i.prompt_tokens:i.prompt_tokens+p,noCache:r?i.prompt_tokens-p:i.prompt_tokens,cacheRead:p,cacheWrite:void 0},outputTokens:{total:i.completion_tokens+q,text:i.completion_tokens,reasoning:q},raw:i}):(0,c.createNullLanguageModelUsage)(),response:n(a),warnings:[],...((null==(g=a.usage)?void 0:g.cost_in_usd_ticks)!=null||null!=a.service_tier)&&{providerMetadata:{xai:{...(null==(h=a.usage)?void 0:h.cost_in_usd_ticks)!=null?{costInUsdTicks:a.usage.cost_in_usd_ticks}:{},...null!=a.service_tier?{serviceTier:a.service_tier}:{}}}}}}}(b.value);return d.success?{type:"text",id:a.batch_request_id,status:"succeeded",result:d.result}:{type:"text",id:a.batch_request_id,status:"failed",error:d.error}}if((null==o?void 0:o.image_generation)!=null){let d=await (0,c.safeValidateTypes)({value:o.image_generation,schema:(0,c.zodSchema)(ab)});if(!d.success)return{type:"image",id:a.batch_request_id,status:"failed",error:{message:"xAI returned an invalid image batch result.",code:"invalid_response"}};if(d.value.data.some(a=>!1===a.respect_moderation))return{type:"image",id:a.batch_request_id,status:"failed",error:{message:"Image generation was blocked due to a content policy violation."}};let e=await this.convertImageBatchResponse(d.value,b);return{type:"image",id:a.batch_request_id,status:"succeeded",result:e}}return al(a.batch_request_id)}async prepareRequest(a){if("text"===a.type){let{args:b,warnings:c}=await $.prepareRequest({modelId:a.modelId,options:a.options});return{endpoint:"/v1/responses",body:b,warnings:c}}let{prompt:b,n:d,size:e,aspectRatio:f,seed:g,files:h,mask:i,providerOptions:j}=a.options,l=[];null!=e&&l.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),null!=g&&l.push({type:"unsupported",feature:"seed"}),null!=i&&l.push({type:"unsupported",feature:"mask"});let m=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:j,schema:k}),n=(null!=h?h:[]).map(c.convertImageModelFileToDataUri),o={model:a.modelId,prompt:b,n:d,response_format:"b64_json"};return null!=f&&(o.aspect_ratio=f),(null==m?void 0:m.output_format)!=null&&(o.output_format=m.output_format),(null==m?void 0:m.sync_mode)!=null&&(o.sync_mode=m.sync_mode),(null==m?void 0:m.aspect_ratio)!=null&&null==f&&(o.aspect_ratio=m.aspect_ratio),(null==m?void 0:m.resolution)!=null&&(o.resolution=m.resolution),(null==m?void 0:m.quality)!=null&&(o.quality=m.quality),(null==m?void 0:m.user)!=null&&(o.user=m.user),1===n.length?o.image={url:n[0],type:"image_url"}:n.length>1&&(o.images=n.map(a=>({url:a,type:"image_url"}))),{endpoint:(null==h?void 0:h.length)?"/v1/images/edits":"/v1/images/generations",body:o,warnings:l}}async convertImageBatchResponse(a,d){var e;return{images:a.data.every(a=>null!=a.b64_json)?a.data.map(a=>a.b64_json):await Promise.all(a.data.map(async a=>{if(null!=a.b64_json)return(0,c.convertBase64ToUint8Array)(a.b64_json);if(null==a.url)throw new b.InvalidArgumentError({argument:"batchResult",message:"xAI returned an image without data or a URL."});let{value:e}=await (0,c.getFromApi)({url:a.url,validateUrl:!0,trustedOrigin:this.options.config.baseURL,abortSignal:d,failedResponseHandler:j,successfulResponseHandler:(0,c.createBinaryResponseHandler)(),fetch:this.options.config.fetch});return e})),warnings:[],response:{timestamp:new Date,modelId:"",headers:void 0},providerMetadata:{xai:{images:a.data.map(a=>null!=a.revised_prompt?{revisedPrompt:a.revised_prompt}:{}),...(null==(e=a.usage)?void 0:e.cost_in_usd_ticks)!=null?{costInUsdTicks:a.usage.cost_in_usd_ticks}:{}}}}}getUrl(a){var b;return`${null!=(b=this.options.config.baseURL)?b:"https://api.x.ai/v1"}${a}`}};function ak(a){var b,d,e,f,g,h;let i=(0,c.normalizeBatchRequestCounts)({total:null==(b=a.state)?void 0:b.num_requests,pending:null==(d=a.state)?void 0:d.num_pending,completed:null==(e=a.state)?void 0:e.num_success,failed:(null==(f=a.state)?void 0:f.num_error)!=null&&(null==(g=a.state)?void 0:g.num_cancelled)!=null?a.state.num_error+a.state.num_cancelled:void 0}),j=null!=a.cancel_time||null!=a.cancel_by_xai_message,k=function(a){if(null==a)return!1;let b=Date.parse(a);return!Number.isNaN(b)&&b<=Date.now()}(a.expire_time);return{status:j||k?"failed":null!=i&&i.total>0&&0===i.pending?"completed":"pending",...null!=i?{requestCounts:i}:{},...j?{error:{message:null!=(h=a.cancel_by_xai_message)?h:`xAI batch "${a.batch_id}" was cancelled.`,code:"batch_cancelled"}}:k?{error:{message:`xAI batch "${a.batch_id}" expired.`,code:"batch_expired"}}:{},...null!=a.create_time?{createdAt:a.create_time}:{},...null!=a.expire_time?{expiresAt:a.expire_time}:{}}}function al(a){return{type:"text",id:a,status:"failed",error:{message:"xAI returned an invalid Responses batch result.",code:"invalid_response"}}}function am(a){var b;let c={};null!=a.instructions&&(c.instructions=a.instructions),null!=a.voice&&(c.voice=a.voice);let d={};if(null!=a.inputAudioFormat&&(d.input={format:{type:a.inputAudioFormat.type,...null!=a.inputAudioFormat.rate?{rate:a.inputAudioFormat.rate}:{}}}),null!=a.outputAudioFormat&&(d.output={format:{type:a.outputAudioFormat.type,...null!=a.outputAudioFormat.rate?{rate:a.outputAudioFormat.rate}:{}}}),Object.keys(d).length>0&&(c.audio=d),null!=a.turnDetection)if("disabled"===a.turnDetection.type)c.turn_detection=null;else{let b={type:"server_vad"};null!=a.turnDetection.threshold&&(b.threshold=a.turnDetection.threshold),null!=a.turnDetection.silenceDurationMs&&(b.silence_duration_ms=a.turnDetection.silenceDurationMs),null!=a.turnDetection.prefixPaddingMs&&(b.prefix_padding_ms=a.turnDetection.prefixPaddingMs),c.turn_detection=b}if(null!=a.tools&&a.tools.length>0&&(c.tools=a.tools.map(a=>({type:a.type,name:a.name,description:a.description,parameters:a.parameters}))),null!=a.providerOptions){let d=a.providerOptions;if(Array.isArray(d.tools)){let a=null!=(b=c.tools)?b:[];c.tools=[...a,...d.tools]}for(let[a,b]of Object.entries(d))"tools"!==a&&(c[a]=b)}return c}var an=class{constructor(a,b){this.specificationVersion="v4",this.modelId=a,this.provider=b.provider,this.config=b}async doCreateClientSecret(a){var b;let c=null!=(b=this.config.fetch)?b:fetch,d=`${this.config.baseURL}/realtime/client_secrets`,e={};null!=a.expiresAfterSeconds&&(e.expires_after={seconds:a.expiresAfterSeconds});let f=await c(d,{method:"POST",headers:{...this.config.headers(),"Content-Type":"application/json"},body:JSON.stringify(e)});if(!f.ok){let a=await f.text();throw Error(`xAI realtime client secret request failed: ${f.status} ${a}`)}let g=await f.json();return{token:g.value,url:`wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`,expiresAt:g.expires_at}}getWebSocketConfig(a){return{url:a.url,protocols:[`xai-client-secret.${a.token}`]}}parseServerEvent(a){return function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;let u=a.type;switch(u){case"session.created":return{type:"session-created",sessionId:null==(b=a.session)?void 0:b.id,raw:a};case"session.updated":return{type:"session-updated",raw:a};case"conversation.created":case"mcp_list_tools.in_progress":case"mcp_list_tools.completed":case"mcp_list_tools.failed":case"response.mcp_call_arguments.delta":case"response.mcp_call_arguments.done":case"response.mcp_call.in_progress":case"response.mcp_call.completed":case"response.mcp_call.failed":default:return{type:"custom",rawType:u,raw:a};case"input_audio_buffer.speech_started":return{type:"speech-started",itemId:a.item_id,raw:a};case"input_audio_buffer.speech_stopped":return{type:"speech-stopped",itemId:a.item_id,raw:a};case"input_audio_buffer.committed":return{type:"audio-committed",itemId:a.item_id,previousItemId:a.previous_item_id,raw:a};case"conversation.item.added":return{type:"conversation-item-added",itemId:null!=(d=null==(c=a.item)?void 0:c.id)?d:a.item_id,item:a.item,raw:a};case"conversation.item.input_audio_transcription.completed":return{type:"input-transcription-completed",itemId:a.item_id,transcript:null!=(e=a.transcript)?e:"",raw:a};case"response.created":return{type:"response-created",responseId:null!=(g=null==(f=a.response)?void 0:f.id)?g:a.response_id,raw:a};case"response.done":return{type:"response-done",responseId:null!=(i=null==(h=a.response)?void 0:h.id)?i:a.response_id,status:null!=(k=null==(j=a.response)?void 0:j.status)?k:"completed",raw:a};case"response.output_item.added":return{type:"output-item-added",responseId:a.response_id,itemId:null!=(m=null==(l=a.item)?void 0:l.id)?m:a.item_id,raw:a};case"response.output_item.done":return{type:"output-item-done",responseId:a.response_id,itemId:null!=(o=null==(n=a.item)?void 0:n.id)?o:a.item_id,raw:a};case"response.content_part.added":return{type:"content-part-added",responseId:a.response_id,itemId:a.item_id,raw:a};case"response.content_part.done":return{type:"content-part-done",responseId:a.response_id,itemId:a.item_id,raw:a};case"response.output_audio.delta":return{type:"audio-delta",responseId:a.response_id,itemId:a.item_id,delta:a.delta,raw:a};case"response.output_audio.done":return{type:"audio-done",responseId:a.response_id,itemId:a.item_id,raw:a};case"response.output_audio_transcript.delta":return{type:"audio-transcript-delta",responseId:a.response_id,itemId:a.item_id,delta:a.delta,raw:a};case"response.output_audio_transcript.done":return{type:"audio-transcript-done",responseId:a.response_id,itemId:a.item_id,transcript:a.transcript,raw:a};case"response.text.delta":return{type:"text-delta",responseId:a.response_id,itemId:a.item_id,delta:a.delta,raw:a};case"response.text.done":return{type:"text-done",responseId:a.response_id,itemId:a.item_id,text:a.text,raw:a};case"response.function_call_arguments.delta":return{type:"function-call-arguments-delta",responseId:a.response_id,itemId:a.item_id,callId:a.call_id,delta:a.delta,raw:a};case"response.function_call_arguments.done":return{type:"function-call-arguments-done",responseId:a.response_id,itemId:a.item_id,callId:a.call_id,name:a.name,arguments:a.arguments,raw:a};case"error":return{type:"error",message:null!=(r=null!=(q=null==(p=a.error)?void 0:p.message)?q:a.message)?r:"Unknown error",code:null!=(t=null==(s=a.error)?void 0:s.code)?t:a.code,raw:a}}}(a)}serializeClientEvent(a){switch(a.type){case"session-update":return{type:"session.update",session:am(a.config)};case"input-audio-append":return{type:"input_audio_buffer.append",audio:a.audio};case"input-audio-commit":return{type:"input_audio_buffer.commit"};case"input-audio-clear":return{type:"input_audio_buffer.clear"};case"conversation-item-create":{let b=a.item;switch(b.type){case"text-message":return{type:"conversation.item.create",item:{type:"message",role:b.role,content:[{type:"input_text",text:b.text}]}};case"audio-message":return{type:"conversation.item.create",item:{type:"message",role:b.role,content:[{type:"input_audio",audio:b.audio}]}};case"function-call-output":return{type:"conversation.item.create",item:{type:"function_call_output",call_id:b.callId,output:b.output}}}break}case"conversation-item-truncate":break;case"response-create":return{type:"response.create",...null!=a.options?{response:{...null!=a.options.modalities?{modalities:a.options.modalities}:{},...null!=a.options.instructions?{instructions:a.options.instructions}:{}}}:{}};case"response-cancel":return{type:"response.cancel"}}}buildSessionConfig(a){return am(a)}},ao=e.z.object({output:e.z.string().describe("the output of the code execution"),error:e.z.string().optional().describe("any error that occurred")}),ap=(0,c.createProviderExecutedToolFactory)({id:"xai.code_execution",inputSchema:e.z.object({}).describe("no input parameters"),outputSchema:ao}),aq=e.z.object({description:e.z.string().describe("description of the image"),objects:e.z.array(e.z.string()).optional().describe("objects detected in the image")}),ar=(0,c.createProviderExecutedToolFactory)({id:"xai.view_image",inputSchema:e.z.object({}).describe("no input parameters"),outputSchema:aq}),as=e.z.object({transcript:e.z.string().optional().describe("transcript of the video"),description:e.z.string().describe("description of the video content"),duration:e.z.number().optional().describe("duration in seconds")}),at=(0,c.createProviderExecutedToolFactory)({id:"xai.view_x_video",inputSchema:e.z.object({}).describe("no input parameters"),outputSchema:as}),au={codeExecution:(a={})=>ap(a),fileSearch:a=>J(a),imageGeneration:(a={})=>N(a),mcpServer:a=>Q(a),viewImage:(a={})=>ar(a),viewXVideo:(a={})=>at(a),webSearch:(a={})=>T(a),xSearch:(a={})=>W(a)},av=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.looseObject({teamId:e.z.string().optional(),filePath:e.z.string().optional(),expiresAfter:e.z.number().int().min(3600).max(2592e3).optional()})));function aw(a){let b=encodeURIComponent(a);return"."===b?"%252E":".."===b?"%252E%252E":b}var ax=class{constructor(a){this.config=a,this.specificationVersion="v4"}get provider(){return this.config.provider}getFileId(a){let c=a.xai;if(null==c||""===c.trim())throw new b.InvalidArgumentError({argument:"file",message:"file reference is missing an 'xai' file id."});return c}getHeaders(a){return(0,c.combineHeaders)(this.config.headers(),a)}async uploadFile({data:a,mediaType:b,filename:d,abortSignal:e,headers:f,providerOptions:g}){var h,i;let k,l;try{k=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:g,schema:av})}catch(b){throw"stream"===a.type&&await a.stream.cancel(b).catch(()=>{}),b}let m=this.getHeaders(f),n=`${this.config.baseURL}/files`;if("stream"===a.type){let f=[];(null==k?void 0:k.expiresAfter)!=null&&f.push({type:"field",name:"expires_after",value:String(k.expiresAfter)}),(null==k?void 0:k.teamId)!=null&&f.push({type:"field",name:"team_id",value:k.teamId}),f.push({type:"file",name:"file",filename:d,mediaType:b,content:a.stream}),{value:l}=await (0,c.postMultipartStreamToApi)({url:n,headers:m,parts:f,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(o),abortSignal:e,fetch:this.config.fetch})}else{let f=new Blob([(0,c.convertInlineFileDataToUint8Array)(a)],{type:b}),g=new FormData;(null==k?void 0:k.expiresAfter)!=null&&g.append("expires_after",String(k.expiresAfter)),(null==k?void 0:k.teamId)!=null&&g.append("team_id",k.teamId),null!=d?g.append("file",f,d):g.append("file",f),{value:l}=await (0,c.postFormDataToApi)({url:n,headers:m,formData:g,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(o),abortSignal:e,fetch:this.config.fetch})}return{warnings:[],providerReference:{xai:l.id},...(null!=(h=l.filename)?h:d)?{filename:null!=(i=l.filename)?i:d}:{},...null!=b?{mediaType:b}:{},...null!=l.bytes?{byteSize:l.bytes}:{},...null!=l.created_at?{createdAt:new Date(1e3*l.created_at)}:{},...null!=l.expires_at?{expiresAt:new Date(1e3*l.expires_at)}:{},providerMetadata:{xai:this.toFileMetadata(l)}}}async getFileMetadata({file:a,abortSignal:b,headers:d}){let e=this.getFileId(a),{value:f}=await (0,c.getFromApi)({url:`${this.config.baseURL}/files/${aw(e)}`,headers:this.getHeaders(d),failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(o),abortSignal:b,fetch:this.config.fetch,validateUrl:!1});return{warnings:[],providerReference:{xai:f.id},...null!=f.filename?{filename:f.filename}:{},...null!=f.bytes?{byteSize:f.bytes}:{},...null!=f.created_at?{createdAt:new Date(1e3*f.created_at)}:{},...null!=f.expires_at?{expiresAt:new Date(1e3*f.expires_at)}:{},providerMetadata:{xai:this.toFileMetadata(f)}}}async downloadFile({file:a,abortSignal:b,headers:d}){var e;let f=this.getFileId(a),{value:g,responseHeaders:h}=await (0,c.getFromApi)({url:`${this.config.baseURL}/files/${aw(f)}/content`,headers:this.getHeaders(d),failedResponseHandler:j,successfulResponseHandler:(0,c.createBinaryStreamResponseHandler)(),abortSignal:b,fetch:this.config.fetch,validateUrl:!1}),i=null==(e=null==h?void 0:h["content-type"])?void 0:e.split(";")[0].trim();return{warnings:[],content:g,...i?{mediaType:i}:{}}}async deleteFile({file:a,abortSignal:b,headers:d}){let e=this.getFileId(a),{value:f}=await (0,c.deleteFromApi)({url:`${this.config.baseURL}/files/${aw(e)}`,headers:this.getHeaders(d),failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(p),abortSignal:b,fetch:this.config.fetch});return{warnings:[],providerReference:{xai:f.id},deleted:f.deleted}}toFileMetadata(a){return{...null!=a.filename?{filename:a.filename}:{},...null!=a.purpose?{purpose:a.purpose}:{},...null!=a.bytes?{bytes:a.bytes}:{},...null!=a.created_at?{createdAt:a.created_at}:{},...null!=a.status?{status:a.status}:{},...null!=a.expires_at?{expiresAt:a.expires_at}:{}}}},ay=e.z.string().min(1),az=e.z.enum(["480p","720p","1080p"]),aA=e.z.enum(["edit-video","extend-video","reference-to-video"]),aB={pollIntervalMs:e.z.number().positive().nullish(),pollTimeoutMs:e.z.number().positive().nullish(),resolution:az.nullish()},aC=e.z.looseObject({mode:aA.optional(),videoUrl:ay.optional(),referenceImageUrls:e.z.array(ay).min(1).max(7).optional(),referenceVoiceIds:e.z.array(ay).max(3).optional(),user:e.z.string().optional(),...aB}),aD=(0,c.lazySchema)(()=>(0,c.zodSchema)(aC)),aE={"1920x1080":"1080p","1280x720":"720p","854x480":"480p","640x480":"480p"};function aF(a){var b,c;return null==(c=null==(b=a.frameImages)?void 0:b.find(a=>"first_frame"===a.frameType))?void 0:c.image}var aG=a=>null!=a.mediaType&&"video"===(0,c.getTopLevelMediaType)(a.mediaType),aH=a=>null==a.mediaType||"image"===(0,c.getTopLevelMediaType)(a.mediaType);function aI(a){if("url"===a.type)return a.url;let b="string"==typeof a.data?a.data:(0,c.convertUint8ArrayToBase64)(a.data);return`data:${a.mediaType};base64,${b}`}function aJ(a){var b,c;return null!=(c=null==(b=a.inputReferences)?void 0:b.some(aH))&&c}var aK=class{constructor(a,b){this.modelId=a,this.config=b,this.specificationVersion="v4",this.maxVideosPerCall=1}get provider(){return this.config.provider}async buildRequestBody(a){var b,d,e;let f=[],g=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:a.providerOptions,schema:aD}),h=function(a,b){if((null==b?void 0:b.mode)!=null)return b.mode;if((null==b?void 0:b.videoUrl)!=null)return"edit-video";let c=null!=a.frameImages&&a.frameImages.length>0,d=(null==b?void 0:b.referenceImageUrls)!=null&&b.referenceImageUrls.length>0;if(!c&&(aJ(a)||d))return"reference-to-video"}(a,g),i="edit-video"===h,j="extend-video"===h,k="reference-to-video"===h;null!=a.fps&&f.push({type:"unsupported",feature:"fps",details:"xAI video models do not support custom FPS."}),null!=a.seed&&f.push({type:"unsupported",feature:"seed",details:"xAI video models do not support seed."}),null!=a.n&&a.n>1&&f.push({type:"unsupported",feature:"n",details:"xAI video models do not support generating multiple videos per call. Only 1 video will be generated."}),i&&null!=a.duration&&f.push({type:"unsupported",feature:"duration",details:"xAI video editing does not support custom duration."}),i&&null!=a.aspectRatio&&f.push({type:"unsupported",feature:"aspectRatio",details:"xAI video editing does not support custom aspect ratio."}),i&&((null==g?void 0:g.resolution)!=null||null!=a.resolution)&&f.push({type:"unsupported",feature:"resolution",details:"xAI video editing does not support custom resolution."}),j&&null!=a.aspectRatio&&f.push({type:"unsupported",feature:"aspectRatio",details:"xAI video extension does not support custom aspect ratio."}),j&&((null==g?void 0:g.resolution)!=null||null!=a.resolution)&&f.push({type:"unsupported",feature:"resolution",details:"xAI video extension does not support custom resolution."});let l={model:this.modelId,prompt:a.prompt},m=!i&&!j;if(i||null==a.duration||(l.duration=a.duration),i||j||null==a.aspectRatio||(l.aspect_ratio=a.aspectRatio),m&&(null==g?void 0:g.resolution)!=null)l.resolution=g.resolution;else if(m&&null!=a.resolution){let b=aE[a.resolution];null!=b?l.resolution=b:f.push({type:"unsupported",feature:"resolution",details:`Unrecognized resolution "${a.resolution}". Use providerOptions.xai.resolution with "480p", "720p", or "1080p" instead.`})}i&&(l.video={url:g.videoUrl}),j&&(l.video={url:g.videoUrl});let n=null!=(b=aF(a))?b:a.image;if(null!=n)if(aG(n)){let b=null!=aF(a);f.push({type:"unsupported",feature:b?"frameImages":"image",details:'xAI does not accept a video as a start/frame image. The video was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video instead.'})}else l.image={url:aI(n)};let o=null==(e=null==(d=a.frameImages)?void 0:d.find(a=>"last_frame"===a.frameType))?void 0:e.image;if(null!=o&&f.push({type:"unsupported",feature:"frameImages",details:aG(o)?'xAI does not accept a video as a start/frame image. The video last frame was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video instead.':'xAI video models do not support last_frame. Use providerOptions.xai.mode "extend-video" to continue from a video\'s last frame. The last frame image was ignored.'}),k){let b=function(a,b,c){if(null!=a.inputReferences&&a.inputReferences.length>0){let b=[];for(let d of a.inputReferences){if(!aH(d)){c.push({type:"unsupported",feature:"inputReferences",details:aG(d)?'xAI reference-to-video accepts image references only. The video reference was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video.':"xAI reference-to-video accepts image references only. The non-image reference was ignored."});continue}b.push(d)}return b.length>0?b.map(a=>({url:aI(a)})):void 0}if((null==b?void 0:b.referenceImageUrls)!=null&&b.referenceImageUrls.length>0)return b.referenceImageUrls.map(a=>({url:a}))}(a,g,f);null!=b?l.reference_images=b:f.push({type:"unsupported",feature:"referenceImages",details:"xAI reference-to-video requires at least one image reference. The video will be generated without reference images."});let c=null==g?void 0:g.referenceVoiceIds;null!=c&&c.length>0&&(l.reference_audios=c.map(a=>({voice_id:a}))),"1080p"===l.resolution&&(f.push({type:"unsupported",feature:"resolution",details:"xAI reference-to-video is limited to 720p. The request was downgraded from 1080p to 720p."}),l.resolution="720p")}if("1080p"===l.resolution&&"grok-imagine-video"===this.modelId&&f.push({type:"unsupported",feature:"resolution",details:'xAI model "grok-imagine-video" does not support 1080p. Use "grok-imagine-video-1.5" for 1080p, or a lower resolution. The request was sent with 1080p.'}),null!=a.inputReferences&&a.inputReferences.length>0&&!k&&f.push({type:"unsupported",feature:"inputReferences",details:aJ(a)?"xAI only supports inputReferences for reference-to-video generation. The reference images were ignored.":"xAI reference-to-video requires at least one image reference. The references were ignored."}),(null==g?void 0:g.referenceVoiceIds)!=null&&g.referenceVoiceIds.length>0&&!k&&f.push({type:"unsupported",feature:"referenceVoiceIds",details:"xAI only supports reference voices for reference-to-video generation. The reference voices were ignored."}),j||(null==g?void 0:g.user)===void 0||(l.user=g.user),null!=g)for(let[a,b]of Object.entries(g))["mode","pollIntervalMs","pollTimeoutMs","resolution","videoUrl","referenceImageUrls","referenceVoiceIds","user"].includes(a)||(l[a]=b);return{body:l,warnings:f,xaiOptions:g,isEdit:i,isExtension:j,hasReferenceImages:k,effectiveMode:h}}async doStart(a){var d,e,f,g;let h,i=null!=(f=null==(e=null==(d=this.config._internal)?void 0:d.currentDate)?void 0:e.call(d))?f:new Date,{body:k,warnings:l,isEdit:m,isExtension:n}=await this.buildRequestBody(a),o=null!=(g=this.config.baseURL)?g:"https://api.x.ai/v1";h=m?`${o}/videos/edits`:n?`${o}/videos/extensions`:`${o}/videos/generations`;let{value:p,responseHeaders:q}=await (0,c.postJsonToApi)({url:h,headers:(0,c.combineHeaders)(this.config.headers(),a.headers),body:k,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(aL),abortSignal:a.abortSignal,fetch:this.config.fetch}),r=p.request_id;if(!r)throw new b.AISDKError({name:"XAI_VIDEO_GENERATION_ERROR",message:"No request_id returned from xAI API."});return{operation:{requestId:r},warnings:l,response:{timestamp:i,modelId:this.modelId,headers:q}}}async doStatus(a){var b,d,e,f,g,h,i,k,l,m,n;let o,p=null!=(e=null==(d=null==(b=this.config._internal)?void 0:b.currentDate)?void 0:d.call(b))?e:new Date,{requestId:q}=a.operation,r=null!=(f=this.config.baseURL)?f:"https://api.x.ai/v1",{value:s,responseHeaders:t}=await (0,c.getFromApi)({url:`${r}/videos/${"."===(o=encodeURIComponent(q))?"%252E":".."===o?"%252E%252E":o}`,validateUrl:!1,headers:(0,c.combineHeaders)(this.config.headers(),a.headers),successfulResponseHandler:aQ,failedResponseHandler:j,abortSignal:a.abortSignal,fetch:this.config.fetch});if("expired"===s.status)return{status:"error",error:"Video generation request expired.",response:{timestamp:p,modelId:this.modelId,headers:t}};if("failed"===s.status){let a=null!=(i=null==(g=s.error)?void 0:g.message)?i:null==(h=s.error)?void 0:h.code;return{status:"error",error:null!=a?`Video generation failed: ${a}`:"Video generation failed.",response:{timestamp:p,modelId:this.modelId,headers:t}}}return"done"===s.status||null==s.status&&(null==(k=s.video)?void 0:k.url)?(null==(l=s.video)?void 0:l.respect_moderation)===!1?{status:"error",error:"Video generation was blocked due to a content policy violation.",response:{timestamp:p,modelId:this.modelId,headers:t}}:(null==(m=s.video)?void 0:m.url)?{status:"completed",videos:[{type:"url",url:s.video.url,mediaType:"video/mp4"}],warnings:[],response:{timestamp:p,modelId:this.modelId,headers:t},providerMetadata:{xai:{requestId:q,videoUrl:s.video.url,...null!=s.video.duration?{duration:s.video.duration}:{},...(null==(n=s.usage)?void 0:n.cost_in_usd_ticks)!=null?{costInUsdTicks:s.usage.cost_in_usd_ticks}:{},...null!=s.progress?{progress:s.progress}:{}}}}:{status:"error",error:"Video generation completed but no video URL was returned.",response:{timestamp:p,modelId:this.modelId,headers:t}}:{status:"pending",response:{timestamp:p,modelId:this.modelId,headers:t}}}},aL=e.z.object({request_id:e.z.string().nullish()}),aM=e.z.object({status:e.z.string().nullish(),video:e.z.object({url:e.z.string(),duration:e.z.number().nullish(),respect_moderation:e.z.boolean().nullish()}).nullish(),model:e.z.string().nullish(),usage:e.z.object({cost_in_usd_ticks:e.z.number().nullish()}).nullish(),progress:e.z.number().nullish(),error:e.z.object({code:e.z.string().nullish(),message:e.z.string().nullish()}).nullish()}),aN=(0,c.createJsonResponseHandler)(aM),aO=new TextDecoder;async function aP({response:a,url:d,requestBodyValues:e}){if(null==a.body)return"";let f=a.body.getReader(),g=[],h=0;try{for(;;){let{done:i,value:j}=await f.read();if(i)break;if((h+=j.length)>1048576)throw new b.APICallError({message:"xAI video status response exceeded 1048576 bytes",url:d,requestBodyValues:e,statusCode:a.status,responseHeaders:(0,c.extractResponseHeaders)(a)});g.push(j)}}finally{f.releaseLock()}let i=new Uint8Array(h),j=0;for(let a of g)i.set(a,j),j+=a.length;return aO.decode(i)}var aQ=async a=>{if(202===a.response.status){let b=(0,c.extractResponseHeaders)(a.response),d=await aP(a);if(0===d.trim().length)return{responseHeaders:b,value:{status:"pending"}};let e=await (0,c.safeParseJSON)({text:d,schema:aM});return{responseHeaders:b,value:e.success?e.value:{status:"pending"}}}return aN(a)},aR=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({sampleRate:e.z.union([e.z.literal(8e3),e.z.literal(16e3),e.z.literal(22050),e.z.literal(24e3),e.z.literal(44100),e.z.literal(48e3)]).nullish(),bitRate:e.z.union([e.z.literal(32e3),e.z.literal(64e3),e.z.literal(96e3),e.z.literal(128e3),e.z.literal(192e3)]).nullish(),optimizeStreamingLatency:e.z.union([e.z.literal(0),e.z.literal(1),e.z.literal(2)]).nullish(),textNormalization:e.z.boolean().nullish(),withTimestamps:e.z.boolean().nullish(),replace:e.z.record(e.z.string(),e.z.string()).nullish()}))),aS=class a{constructor(a,b){this.modelId=a,this.config=b,this.specificationVersion="v4"}static[d.WORKFLOW_SERIALIZE](a){return(0,c.serializeModelOptions)({modelId:a.modelId,config:a.config})}static[d.WORKFLOW_DESERIALIZE](b){return new a(b.modelId,b.config)}get provider(){return this.config.provider}async getArgs({text:a,voice:b="eve",outputFormat:d="mp3",instructions:e,speed:f,language:g="auto",providerOptions:h}){let i=[],j=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:h,schema:aR}),k="mp3";["mp3","wav","pcm","mulaw","alaw"].includes(d)?k=d:i.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${d}. Using mp3 instead.`}),null!=e&&i.push({type:"unsupported",feature:"instructions",details:"xAI speech models do not support the `instructions` option. Use xAI speech tags in `text` to control delivery."});let l={codec:k};return(null==j?void 0:j.sampleRate)!=null&&(l.sample_rate=j.sampleRate),(null==j?void 0:j.bitRate)!=null&&("mp3"===k?l.bit_rate=j.bitRate:i.push({type:"unsupported",feature:"providerOptions",details:"xAI `bitRate` is supported only for mp3 output. It was ignored."})),{requestBody:{text:a,voice_id:b,language:g,output_format:l,speed:f,optimize_streaming_latency:null==j?void 0:j.optimizeStreamingLatency,text_normalization:null==j?void 0:j.textNormalization,with_timestamps:null==j?void 0:j.withTimestamps,replace:null==j?void 0:j.replace},warnings:i,withTimestamps:(null==j?void 0:j.withTimestamps)===!0}}async doGenerate(a){var b,d,e;let f,g,h=null!=(e=null==(d=null==(b=this.config._internal)?void 0:b.currentDate)?void 0:d.call(b))?e:new Date,{requestBody:i,warnings:k,withTimestamps:l}=await this.getArgs(a),{value:m,responseHeaders:n,rawValue:o}=await (0,c.postJsonToApi)({url:`${this.config.baseURL}/tts`,headers:(0,c.combineHeaders)(this.config.headers?await (0,c.resolve)(this.config.headers):void 0,a.headers),body:i,failedResponseHandler:j,successfulResponseHandler:l?(0,c.createJsonResponseHandler)(aT):(0,c.createBinaryResponseHandler)(),abortSignal:a.abortSignal,fetch:this.config.fetch});f=m instanceof Uint8Array?m:null!=(g=m).audio?(0,c.convertBase64ToUint8Array)(g.audio):new Uint8Array(0);let p=null==n?void 0:n["x-trace-id"];return{audio:f,warnings:k,request:{body:JSON.stringify(i)},response:{timestamp:h,modelId:this.modelId,headers:n,body:o},providerMetadata:{xai:{...null!=p?{traceId:p}:{},...(null==g?void 0:g.duration)!=null?{duration:g.duration}:{},...(null==g?void 0:g.content_type)!=null?{contentType:g.content_type}:{},...(null==g?void 0:g.audio_timestamps)!=null?{audioTimestamps:{graphChars:g.audio_timestamps.graph_chars,graphTimes:g.audio_timestamps.graph_times}}:{}}}}}},aT=e.z.object({audio:e.z.string().nullish(),content_type:e.z.string().nullish(),duration:e.z.number().nullish(),audio_timestamps:e.z.object({graph_chars:e.z.array(e.z.string()),graph_times:e.z.array(e.z.tuple([e.z.number(),e.z.number()]))}).nullish()}),aU=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({audioFormat:e.z.enum(["pcm","mulaw","alaw"]).nullish(),sampleRate:e.z.union([e.z.literal(8e3),e.z.literal(16e3),e.z.literal(22050),e.z.literal(24e3),e.z.literal(44100),e.z.literal(48e3)]).nullish(),language:e.z.string().nullish(),format:e.z.boolean().nullish(),multichannel:e.z.boolean().nullish(),channels:e.z.number().int().min(2).max(8).nullish(),diarize:e.z.boolean().nullish(),keyterm:e.z.union([e.z.string(),e.z.array(e.z.string())]).nullish(),fillerWords:e.z.boolean().nullish(),streaming:e.z.object({interimResults:e.z.boolean().optional(),endpointing:e.z.number().int().min(0).max(5e3).optional(),smartTurn:e.z.number().min(0).max(1).optional(),smartTurnTimeout:e.z.number().int().min(1).max(5e3).optional()}).optional()}))),aV=class a{constructor(a,b){this.modelId=a,this.config=b,this.specificationVersion="v4"}static[d.WORKFLOW_SERIALIZE](a){return(0,c.serializeModelOptions)({modelId:a.modelId,config:a.config})}static[d.WORKFLOW_DESERIALIZE](b){return new a(b.modelId,b.config)}get provider(){return this.config.provider}async getArgs({audio:a,mediaType:b,providerOptions:d}){let e=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:d,schema:aU}),f=new FormData;for(let[a,b]of Object.entries({audio_format:null==e?void 0:e.audioFormat,sample_rate:null==e?void 0:e.sampleRate,language:null==e?void 0:e.language,format:null==e?void 0:e.format,multichannel:null==e?void 0:e.multichannel,channels:null==e?void 0:e.channels,diarize:null==e?void 0:e.diarize,filler_words:null==e?void 0:e.fillerWords}))null!=b&&f.append(a,String(b));if((null==e?void 0:e.keyterm)!=null)for(let a of Array.isArray(e.keyterm)?e.keyterm:[e.keyterm])f.append("keyterm",a);let g=a instanceof Uint8Array?new Blob([a]):new Blob([(0,c.convertBase64ToUint8Array)(a)]),h=(0,c.mediaTypeToExtension)(b);return f.append("file",new File([g],"audio",{type:b}),`audio.${h}`),{formData:f,warnings:[]}}async doGenerate(a){var b,d,e,f,g,h,i,k,l;let m=null!=(e=null==(d=null==(b=this.config._internal)?void 0:b.currentDate)?void 0:d.call(b))?e:new Date,{formData:n,warnings:o}=await this.getArgs(a),{value:p,responseHeaders:q,rawValue:r}=await (0,c.postFormDataToApi)({url:`${null!=(f=this.config.baseURL)?f:"https://api.x.ai/v1"}/stt`,headers:(0,c.combineHeaders)(null==(h=(g=this.config).headers)?void 0:h.call(g),a.headers),formData:n,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(aX),abortSignal:a.abortSignal,fetch:this.config.fetch});return{text:p.text,segments:null!=(k=null==(i=p.words)?void 0:i.map(a=>({text:a.text,startSecond:a.start,endSecond:a.end})))?k:[],language:p.language||void 0,durationInSeconds:null!=(l=p.duration)?l:void 0,warnings:o,response:{timestamp:m,modelId:this.modelId,headers:q,body:r}}}async doStream(a){var d,e,f,g,h,i,j,k;let l=null!=(f=null==(e=null==(d=this.config._internal)?void 0:d.currentDate)?void 0:e.call(d))?f:new Date,m=[],n=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:a.providerOptions,schema:aU});if((null==n?void 0:n.multichannel)===!0&&null==n.channels)throw new b.InvalidArgumentError({argument:"providerOptions",message:"providerOptions.xai.channels is required when providerOptions.xai.multichannel is true"});(null==n?void 0:n.format)!=null&&m.push({type:"unsupported",feature:"providerOptions.xai.format",details:"xAI streaming transcription does not support format."}),(null==n?void 0:n.audioFormat)==null&&"audio/pcm"!==(k=a.inputAudioFormat.type)&&"audio/pcmu"!==k&&"audio/pcma"!==k&&m.push({type:"other",message:`Unrecognized inputAudioFormat.type "${a.inputAudioFormat.type}"; falling back to raw PCM encoding. Use audio/pcm, audio/pcmu, or audio/pcma, or set providerOptions.xai.audioFormat explicitly.`});let o=function({baseURL:a,inputAudioFormat:b,providerOptions:d}){var e,f,g,h,i,j;let k=(0,c.toWebSocketUrl)(`${a}/stt`);if(aW(k,"sample_rate",null!=(e=null==d?void 0:d.sampleRate)?e:b.rate),aW(k,"encoding",null!=(f=null==d?void 0:d.audioFormat)?f:function(a){switch(a){case"audio/pcmu":return"mulaw";case"audio/pcma":return"alaw";default:return"pcm"}}(b.type)),aW(k,"language",null==d?void 0:d.language),aW(k,"diarize",null==d?void 0:d.diarize),aW(k,"filler_words",null==d?void 0:d.fillerWords),aW(k,"multichannel",null==d?void 0:d.multichannel),aW(k,"channels",null==d?void 0:d.channels),aW(k,"interim_results",null==(g=null==d?void 0:d.streaming)?void 0:g.interimResults),aW(k,"endpointing",null==(h=null==d?void 0:d.streaming)?void 0:h.endpointing),aW(k,"smart_turn",null==(i=null==d?void 0:d.streaming)?void 0:i.smartTurn),aW(k,"smart_turn_timeout",null==(j=null==d?void 0:d.streaming)?void 0:j.smartTurnTimeout),(null==d?void 0:d.keyterm)!=null)for(let a of Array.isArray(d.keyterm)?d.keyterm:[d.keyterm])k.searchParams.append("keyterm",a);return k}({baseURL:null!=(g=this.config.baseURL)?g:"https://api.x.ai/v1",inputAudioFormat:a.inputAudioFormat,providerOptions:n}),p=(0,c.combineHeaders)(null==(i=(h=this.config).headers)?void 0:i.call(h),a.headers);return{request:{body:o.toString()},response:{timestamp:l,modelId:this.modelId},stream:function({webSocket:a,url:b,headers:d,warnings:e,language:f,expectedDoneCount:g,audio:h,abortSignal:i,includeRawChunks:j}){let k=!1,l=()=>{};return new ReadableStream({start:m=>{let n,o,p,q=new Map,r=new Map,s=new Map;l=a=>{null!=o?o.cancel().catch(()=>{}):h.cancel().catch(()=>{}),null==p||p.close(a)};let t=a=>{k||(k=!0,l(),m.error(a))},u=async a=>{o=h.getReader();try{for(;;){let{done:b,value:d}=await o.read();if(b||k)break;a.send(d instanceof Uint8Array?d:(0,c.convertBase64ToUint8Array)(d)),await (0,c.waitForWebSocketBufferDrain)(a)}}finally{o.releaseLock(),o=void 0}k||a.send(JSON.stringify({type:"audio.done"}))};p=(0,c.connectToWebSocket)({url:b,headers:d,webSocket:a,abortSignal:i,onAbort:t,onProcessingError:t,onMessageText:async a=>{var b,d,h,i,o,v,w,x,y,z,A;let B=await (0,c.safeParseJSON)({text:a});if(!B.success)return;let C=B.value;switch(j&&m.enqueue({type:"raw",rawValue:C}),C.type){case"transcript.created":{m.enqueue({type:"stream-start",warnings:e});let a=null==p?void 0:p.socket;if(null==a){t(Error("WebSocket is not connected."));break}u(a).catch(t);break}case"transcript.partial":{let a=null==(z=C.channel_index)?void 0:`channel-${z}`,c=null!=(b=C.channel_index)?b:0;if(C.is_final&&C.speech_final){let b={...null!=(A=C).start?{startSecond:A.start}:{},...null!=A.start&&null!=A.duration?{endSecond:A.start+A.duration}:{}};C.text&&r.set(c,[...null!=(d=r.get(c))?d:[],C.text]),s.delete(c),m.enqueue({type:"transcript-final",id:a,text:null!=(h=C.text)?h:"",...b,channelIndex:C.channel_index})}else s.set(c,null!=(i=C.text)?i:""),m.enqueue({type:"transcript-partial",id:a,text:null!=(o=C.text)?o:"",startSecond:C.start,durationInSeconds:C.duration,channelIndex:C.channel_index});break}case"transcript.done":{let a=null!=(v=C.channel_index)?v:0,b=[...null!=(w=r.get(a))?w:[],...s.get(a)?[s.get(a)]:[]].join(" ");q.set(a,C.text||b),n=null!=(x=C.duration)?x:n,(()=>{if(k||q.size<g)return;k=!0;let a=[...q.entries()].sort(([a],[b])=>a-b).map(([,a])=>a).join("\n");m.enqueue({type:"finish",text:a,segments:[],language:f,durationInSeconds:n}),m.close(),l(1e3)})();break}case"error":t(Error(null!=(y=C.message)?y:"xAI STT error"))}},onSocketError:()=>{t(Error("xAI streaming transcription error."+(null==a?" Note: the native WebSocket implementation in browsers, Node.js, Deno, and Bun cannot send the Authorization header required by xAI. Pass a header-capable WebSocket implementation (e.g. the 'ws' package) via createXai({ webSocket }).":"")))},onClose:()=>{k||(k=!0,l(),m.close())}})},cancel:()=>{k||(k=!0,l())}})}({webSocket:this.config.webSocket,url:o,headers:p,warnings:m,language:null!=(j=null==n?void 0:n.language)?j:void 0,expectedDoneCount:(null==n?void 0:n.multichannel)===!0?n.channels:1,audio:a.audio,abortSignal:a.abortSignal,includeRawChunks:a.includeRawChunks})}}};function aW(a,b,c){null!=c&&a.searchParams.set(b,String(c))}var aX=e.z.object({text:e.z.string(),language:e.z.string().nullish(),duration:e.z.number().nullish(),words:e.z.array(e.z.object({text:e.z.string(),start:e.z.number(),end:e.z.number()})).nullish()});function aY(a={}){var d;let e=(0,c.withoutTrailingSlash)(null!=(d=a.baseURL)?d:"https://api.x.ai/v1"),f=()=>(0,c.withUserAgentSuffix)({Authorization:`Bearer ${(0,c.loadApiKey)({apiKey:a.apiKey,environmentVariableName:"XAI_API_KEY",description:"xAI API key"})}`,...a.headers},"ai-sdk/xai/5.0.7"),g=b=>new $(b,{provider:"xai.responses",baseURL:e,headers:f,generateId:c.generateId,fetch:a.fetch}),h=b=>new l(b,{provider:"xai.image",baseURL:e,headers:f,fetch:a.fetch}),i=b=>new aK(b,{provider:"xai.video",baseURL:e,headers:f,fetch:a.fetch}),j=b=>new an(b,{provider:"xai.realtime",baseURL:null!=e?e:"https://api.x.ai/v1",headers:f,fetch:a.fetch}),k=()=>new aS("",{provider:"xai.speech",baseURL:e,headers:f,fetch:a.fetch}),m=()=>new aV("",{provider:"xai.transcription",baseURL:e,headers:f,fetch:a.fetch,webSocket:a.webSocket}),n=Object.assign(a=>j(a),{getToken:async a=>{let b=j(a.model),c=await b.doCreateClientSecret({sessionConfig:a.sessionConfig,expiresAfterSeconds:a.expiresAfterSeconds});return{token:c.token,url:c.url,expiresAt:c.expiresAt}}}),o=a=>g(a);return o.specificationVersion="v4",o.languageModel=g,o.responses=g,o.embeddingModel=a=>{throw new b.NoSuchModelError({modelId:a,modelType:"embeddingModel"})},o.textEmbeddingModel=o.embeddingModel,o.imageModel=h,o.image=h,o.videoModel=i,o.video=i,o.experimental_realtime=n,o.speechModel=k,o.speech=k,o.transcriptionModel=m,o.transcription=m,o.files=()=>new ax({provider:"xai.files",baseURL:e,headers:f,fetch:a.fetch}),o.experimental_batch=()=>new aj({provider:"xai.batch",config:{provider:"xai.responses",baseURL:e,headers:f,generateId:c.generateId,fetch:a.fetch}}),o.tools=au,o}aY(),a.s(["createXai",0,aY])},236338,(a,b,c)=>{"use strict";var d=Object.defineProperty,e=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,g=Object.prototype.hasOwnProperty,h={},i={SYMBOL_FOR_REQ_CONTEXT:()=>k,getContext:()=>l};for(var j in i)d(h,j,{get:i[j],enumerable:!0});b.exports=((a,b,c)=>{if(b&&"object"==typeof b||"function"==typeof b)for(let h of f(b))g.call(a,h)||void 0===h||d(a,h,{get:()=>b[h],enumerable:!(c=e(b,h))||c.enumerable});return a})(d({},"__esModule",{value:!0}),h);let k=Symbol.for("@vercel/request-context");function l(){let a=globalThis;return a[k]?.get?.()??{}}},817547,(a,b,c)=>{"use strict";var d=Object.defineProperty,e=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,g=Object.prototype.hasOwnProperty,h={},i={getVercelOidcToken:()=>m,getVercelOidcTokenSync:()=>n};for(var j in i)d(h,j,{get:i[j],enumerable:!0});b.exports=((a,b,c)=>{if(b&&"object"==typeof b||"function"==typeof b)for(let h of f(b))g.call(a,h)||void 0===h||d(a,h,{get:()=>b[h],enumerable:!(c=e(b,h))||c.enumerable});return a})(d({},"__esModule",{value:!0}),h);var k=a.r(236338),l=a.r(580949);async function m(b){let c,d="";try{d=n()}catch(a){c=a}try{let[{getTokenPayload:c,isExpired:e},{refreshToken:f}]=await Promise.all([await a.A(682672),await a.A(966249)]);(!d||e(c(d),b?.expirationBufferMs))&&(await f(b),d=n())}catch(b){let a=c instanceof Error?c.message:"";if(b instanceof Error&&(a=`${a}
|
|
212
|
+
Error message: ${W(b)}`,cause:b}),this[D]=!0,this.value=a,this.context=c}static isInstance(a){return J.hasMarker(a,aK)}static wrap({value:b,cause:c,context:d}){var e,f,g;return a.isInstance(c)&&c.value===b&&(null==(e=c.context)?void 0:e.field)===(null==d?void 0:d.field)&&(null==(f=c.context)?void 0:f.entityName)===(null==d?void 0:d.entityName)&&(null==(g=c.context)?void 0:g.entityId)===(null==d?void 0:d.entityId)?c:new a({value:b,cause:c,context:d})}},aN="AI_UnsupportedFunctionalityError",aO=`vercel.ai.error.${aN}`,aP=Symbol.for(aO),aQ=class extends(G=J,F=aP,G){constructor({functionality:a,message:b=`'${a}' functionality not supported.`}){super({name:aN,message:b}),this[F]=!0,this.functionality=a}static isInstance(a){return J.hasMarker(a,aO)}};function aR(a){return null===a||"string"==typeof a||"number"==typeof a||"boolean"==typeof a||(Array.isArray(a)?a.every(aR):"object"==typeof a&&Object.entries(a).every(([a,b])=>"string"==typeof a&&(void 0===b||aR(b))))}a.s(["AISDKError",0,J,"APICallError",0,N,"EmptyResponseBodyError",0,R,"Experimental_EvaluationUnsupportedQuestionTypeError",0,V,"InvalidArgumentError",0,$,"InvalidPromptError",0,ac,"InvalidResponseDataError",0,ag,"JSONParseError",0,ak,"LoadAPIKeyError",0,ao,"LoadSettingError",0,as,"NoContentGeneratedError",0,aw,"NoSuchModelError",0,aA,"NoSuchProviderReferenceError",0,aE,"TooManyEmbeddingValuesForCallError",0,aI,"TypeValidationError",0,aM,"UnsupportedFunctionalityError",0,aQ,"getErrorMessage",0,W,"isJSONArray",0,function(a){return Array.isArray(a)&&a.every(aR)},"isJSONObject",0,function(a){return null!=a&&"object"==typeof a&&Object.entries(a).every(([a,b])=>"string"==typeof a&&(void 0===b||aR(b)))}])},434451,a=>{"use strict";var b=a.i(404989),c=a.i(527990),d=a.i(53112),e=a.i(912735),f=(0,c.lazySchema)(()=>(0,c.zodSchema)(d.z.object({error:d.z.object({message:d.z.string()})}))),g=(0,c.lazySchema)(()=>(0,c.zodSchema)(d.z.object({id:d.z.string().nullish(),model:d.z.string().nullish(),results:d.z.array(d.z.object({index:d.z.number(),relevance_score:d.z.number()})),usage:d.z.object({prompt_tokens:d.z.number(),completion_tokens:d.z.number(),total_tokens:d.z.number()})}))),h=(0,c.lazySchema)(()=>(0,c.zodSchema)(d.z.object({rankFields:d.z.array(d.z.string()).optional()}))),i=class{constructor(a,b){this.specificationVersion="v4",this.modelId=a,this.config=b}get provider(){return this.config.provider}async doRerank({documents:a,headers:b,query:d,topN:e,abortSignal:i,providerOptions:j}){var k,l;let m=await (0,c.parseProviderOptions)({provider:"togetherai",providerOptions:j,schema:h}),{responseHeaders:n,value:o,rawValue:p}=await (0,c.postJsonToApi)({url:`${this.config.baseURL}/rerank`,headers:(0,c.combineHeaders)(this.config.headers(),b),body:{model:this.modelId,documents:a.values,query:d,top_n:e,rank_fields:null==m?void 0:m.rankFields,return_documents:!1},failedResponseHandler:(0,c.createJsonErrorResponseHandler)({errorSchema:f,errorToMessage:a=>a.error.message}),successfulResponseHandler:(0,c.createJsonResponseHandler)(g),abortSignal:i,fetch:this.config.fetch});return{ranking:o.results.map(a=>({index:a.index,relevanceScore:a.relevance_score})),response:{id:null!=(k=o.id)?k:void 0,modelId:null!=(l=o.model)?l:void 0,headers:n,body:p}}}},j=(0,c.lazySchema)(()=>(0,c.zodSchema)(d.z.looseObject({steps:d.z.number().nullish(),guidance:d.z.number().nullish(),negative_prompt:d.z.string().nullish(),disable_safety_checker:d.z.boolean().nullish()}))),k=new Set(["google/gemini-3-pro-image"]),l=class a{constructor(a,b){this.modelId=a,this.config=b,this.specificationVersion="v4",this.maxImagesPerCall=1}get provider(){return this.config.provider}static[e.WORKFLOW_SERIALIZE](a){return(0,c.serializeModelOptions)({modelId:a.modelId,config:a.config})}static[e.WORKFLOW_DESERIALIZE](b){return new a(b.modelId,b.config)}async doGenerate({prompt:a,n:b,size:d,seed:e,providerOptions:f,headers:g,abortSignal:h,files:i,mask:l}){var o,p,q,r,s;let t,u=[];if(null!=l)throw Error("Together AI does not support mask-based image editing. Use FLUX Kontext models (e.g., black-forest-labs/FLUX.1-kontext-pro) with a reference image and descriptive prompt instead.");null!=d&&u.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support the `aspectRatio` option. Use `size` instead."});let v=null!=(q=null==(p=null==(o=this.config._internal)?void 0:o.currentDate)?void 0:p.call(o))?q:new Date,w=await (0,c.parseProviderOptions)({provider:"togetherai",providerOptions:f,schema:j}),x=k.has(this.modelId),y={...w};x&&(delete y.steps,delete y.guidance,delete y.negative_prompt,delete y.disable_safety_checker,null!=e&&u.push({type:"unsupported",feature:"seed",details:`The ${this.modelId} model does not support the \`seed\` option.`})),null!=i&&i.length>0&&(t=(0,c.convertImageModelFileToDataUri)(i[0]),i.length>1&&u.push({type:"other",message:"Together AI only supports a single input image. Additional images are ignored."}));let z=null==d?void 0:d.split("x"),{value:A,responseHeaders:B}=await (0,c.postJsonToApi)({url:`${this.config.baseURL}/images/generations`,headers:(0,c.combineHeaders)(null==(s=(r=this.config).headers)?void 0:s.call(r),g),body:{model:this.modelId,prompt:a,...null!=e&&!x?{seed:e}:{},...b>1?{n:b}:{},...z&&{width:parseInt(z[0]),height:parseInt(z[1])},...null!=t?{image_url:t}:{},response_format:"base64",...y},failedResponseHandler:(0,c.createJsonErrorResponseHandler)({errorSchema:n,errorToMessage:a=>a.error.message}),successfulResponseHandler:(0,c.createJsonResponseHandler)(m),abortSignal:h,fetch:this.config.fetch});return{images:A.data.map(a=>a.b64_json),warnings:u,response:{timestamp:v,modelId:this.modelId,headers:B}}}},m=d.z.object({data:d.z.array(d.z.object({b64_json:d.z.string()}))}),n=d.z.object({error:d.z.object({message:d.z.string()})});function o(a={}){var d;let e=(0,c.withoutTrailingSlash)(null!=(d=a.baseURL)?d:"https://api.together.xyz/v1/"),f=()=>{var b;return(0,c.withUserAgentSuffix)({Authorization:`Bearer ${(0,c.loadApiKey)({apiKey:null!=(b=a.apiKey)?b:function(){if("u"<typeof process||"string"==typeof process.env.TOGETHER_API_KEY)return;let a=process.env.TOGETHER_AI_API_KEY;return"string"==typeof a&&console.warn("TOGETHER_AI_API_KEY is deprecated and will be removed in a future release. Please use TOGETHER_API_KEY instead."),a}(),environmentVariableName:"TOGETHER_API_KEY",description:"TogetherAI"})}`,...a.headers},"ai-sdk/togetherai/3.0.56")},g=b=>({provider:`togetherai.${b}`,url:({path:a})=>`${e}${a}`,headers:f,fetch:a.fetch}),h=a=>new b.OpenAICompatibleChatLanguageModel(a,{...g("chat"),includeUsage:!0,supportsStructuredOutputs:"deepseek-ai/DeepSeek-V4-Flash-0731"===a}),j=a=>new b.OpenAICompatibleEmbeddingModel(a,g("embedding")),k=a=>new l(a,{...g("image"),baseURL:null!=e?e:"https://api.together.xyz/v1/"}),m=a=>new i(a,{...g("reranking"),baseURL:null!=e?e:"https://api.together.xyz/v1/"}),n=a=>h(a);return n.specificationVersion="v4",n.completionModel=a=>new b.OpenAICompatibleCompletionLanguageModel(a,{...g("completion"),includeUsage:!0}),n.languageModel=h,n.chatModel=h,n.embeddingModel=j,n.textEmbeddingModel=j,n.image=k,n.imageModel=k,n.reranking=m,n.rerankingModel=m,n}o(),a.s(["createTogetherAI",0,o])},655819,a=>{"use strict";var b=a.i(652685),c=a.i(527990),d=a.i(912735),e=a.i(53112),f=e.z.object({error:e.z.object({message:e.z.string(),type:e.z.string().nullish(),param:e.z.any().nullish(),code:e.z.union([e.z.string(),e.z.number()]).nullish()})}),g=e.z.object({code:e.z.string(),error:e.z.string()}),h=e.z.object({error:e.z.string()}),i=e.z.union([f,g,h]),j=(0,c.createJsonErrorResponseHandler)({errorSchema:i,errorToMessage:a=>"string"==typeof a.error?"code"in a?`${a.code}: ${a.error}`:a.error:a.error.message}),k=e.z.object({aspect_ratio:e.z.string().optional(),output_format:e.z.string().optional(),sync_mode:e.z.boolean().optional(),resolution:e.z.enum(["1k","2k"]).optional(),quality:e.z.enum(["low","medium","high"]).optional(),user:e.z.string().optional()}),l=class a{constructor(a,b){this.modelId=a,this.config=b,this.specificationVersion="v4",this.maxImagesPerCall=3}get provider(){return this.config.provider}static[d.WORKFLOW_SERIALIZE](a){return(0,c.serializeModelOptions)({modelId:a.modelId,config:a.config})}static[d.WORKFLOW_DESERIALIZE](b){return new a(b.modelId,b.config)}async doGenerate({prompt:a,n:b,size:d,aspectRatio:e,seed:f,providerOptions:g,headers:h,abortSignal:i,files:l,mask:n}){var o,p,q,r,s,t,u;let v=[];null!=d&&v.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),null!=f&&v.push({type:"unsupported",feature:"seed"}),null!=n&&v.push({type:"unsupported",feature:"mask"});let w=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:g,schema:k}),x=null!=l&&l.length>0,y=x?l.map(a=>(0,c.convertImageModelFileToDataUri)(a)):[],z={model:this.modelId,prompt:a,n:b,response_format:"b64_json"};null!=e&&(z.aspect_ratio=e),(null==w?void 0:w.output_format)!=null&&(z.output_format=w.output_format),(null==w?void 0:w.sync_mode)!=null&&(z.sync_mode=w.sync_mode),(null==w?void 0:w.aspect_ratio)!=null&&null==e&&(z.aspect_ratio=w.aspect_ratio),(null==w?void 0:w.resolution)!=null&&(z.resolution=w.resolution),(null==w?void 0:w.quality)!=null&&(z.quality=w.quality),(null==w?void 0:w.user)!=null&&(z.user=w.user),1===y.length?z.image={url:y[0],type:"image_url"}:y.length>1&&(z.images=y.map(a=>({url:a,type:"image_url"})));let A=null!=(o=this.config.baseURL)?o:"https://api.x.ai/v1",B=null!=(r=null==(q=null==(p=this.config._internal)?void 0:p.currentDate)?void 0:q.call(p))?r:new Date,{value:C,responseHeaders:D}=await (0,c.postJsonToApi)({url:`${A}${x?"/images/edits":"/images/generations"}`,headers:(0,c.combineHeaders)(null==(t=(s=this.config).headers)?void 0:t.call(s),h),body:z,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(m),abortSignal:i,fetch:this.config.fetch});if(C.data.some(a=>!1===a.respect_moderation))throw Error("Image generation was blocked due to a content policy violation.");return{images:C.data.every(a=>null!=a.b64_json)?C.data.map(a=>a.b64_json):await Promise.all(C.data.map(a=>this.downloadImage(a.url,i))),warnings:v,response:{timestamp:B,modelId:this.modelId,headers:D},providerMetadata:{xai:{images:C.data.map(a=>({...a.revised_prompt?{revisedPrompt:a.revised_prompt}:{}})),...(null==(u=C.usage)?void 0:u.cost_in_usd_ticks)!=null?{costInUsdTicks:C.usage.cost_in_usd_ticks}:{}}}}}async downloadImage(a,b){let{value:d}=await (0,c.getFromApi)({url:a,validateUrl:!0,trustedOrigin:this.config.baseURL,abortSignal:b,failedResponseHandler:(0,c.createStatusCodeErrorResponseHandler)(),successfulResponseHandler:(0,c.createBinaryResponseHandler)(),fetch:this.config.fetch});return d}},m=e.z.object({data:e.z.array(e.z.object({url:e.z.string().nullish(),b64_json:e.z.string().nullish(),revised_prompt:e.z.string().nullish(),respect_moderation:e.z.boolean().nullish()})),usage:e.z.object({cost_in_usd_ticks:e.z.number().nullish()}).nullish()});function n({id:a,model:b,created:d,created_at:e}){return(0,c.createLanguageModelResponseMetadata)({id:a,model:b,created:null!=d?d:e})}var o=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({id:e.z.string(),object:e.z.string().nullish(),bytes:e.z.number().nullish(),created_at:e.z.number().nullish(),expires_at:e.z.number().nullish(),filename:e.z.string().nullish(),purpose:e.z.string().nullish(),status:e.z.string().nullish()}))),p=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({id:e.z.string(),object:e.z.string().nullish(),deleted:e.z.boolean()}))),q=/^grok-4\.20(-\d{4})?-(non-)?reasoning$/,r=e.z.object({imageDetail:e.z.enum(["low","high","auto"]).optional()});async function s({prompt:a}){var d,e,f,g,h,i,j,k,l;let m=[],n=[];for(let o of a)switch(o.role){case"system":m.push({role:"system",content:o.content});break;case"user":{let a=[];for(let d of o.content)switch(d.type){case"text":a.push({type:"input_text",text:d.text});break;case"file":switch(d.data.type){case"reference":a.push({type:"input_file",file_id:(0,c.resolveProviderReference)({reference:d.data.reference,provider:"xai"})});break;case"text":throw new b.UnsupportedFunctionalityError({functionality:"text file parts"});case"url":case"data":if("image"===(0,c.getTopLevelMediaType)(d.mediaType)){let b="url"===d.data.type?d.data.url.toString():`data:${(0,c.resolveFullMediaType)({part:d})};base64,${(0,c.convertToBase64)(d.data.data)}`,e=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:d.providerOptions,schema:r});a.push({type:"input_image",image_url:b,...(null==e?void 0:e.imageDetail)!=null&&{detail:e.imageDetail}})}else if("url"===d.data.type)a.push({type:"input_file",file_url:d.data.url.toString()});else throw new b.UnsupportedFunctionalityError({functionality:`file part media type ${d.mediaType} as inline data (xAI Responses requires a URL or a Files API reference for non-image files)`})}break;default:n.push({type:"other",message:"xAI Responses API does not support this content type in user messages"})}m.push({role:"user",content:a});break}case"assistant":for(let a of o.content)switch(a.type){case"text":{let b="string"==typeof(null==(e=null==(d=a.providerOptions)?void 0:d.xai)?void 0:e.itemId)?a.providerOptions.xai.itemId:void 0;m.push({role:"assistant",content:a.text,id:b});break}case"tool-call":{if(a.providerExecuted)break;let b="string"==typeof(null==(g=null==(f=a.providerOptions)?void 0:f.xai)?void 0:g.itemId)?a.providerOptions.xai.itemId:void 0;m.push({type:"function_call",id:null!=b?b:a.toolCallId,call_id:a.toolCallId,name:a.toolName,arguments:JSON.stringify(a.input),status:"completed"});break}case"tool-result":break;case"reasoning":{let b="string"==typeof(null==(i=null==(h=a.providerOptions)?void 0:h.xai)?void 0:i.itemId)?a.providerOptions.xai.itemId:void 0,c="string"==typeof(null==(k=null==(j=a.providerOptions)?void 0:j.xai)?void 0:k.reasoningEncryptedContent)?a.providerOptions.xai.reasoningEncryptedContent:void 0;if(null!=b||null!=c){let d=[];a.text.length>0&&d.push({type:"summary_text",text:a.text}),m.push({type:"reasoning",id:null!=b?b:"",summary:d,status:"completed",...null!=c&&{encrypted_content:c}})}else n.push({type:"other",message:"Reasoning parts without itemId or encrypted content cannot be sent back to xAI. Skipping."});break}case"reasoning-file":case"custom":case"file":n.push({type:"other",message:`xAI Responses API does not support ${a.type} in assistant messages`});break;default:n.push({type:"other",message:"xAI Responses API does not support this content type in assistant messages"})}break;case"tool":for(let a of o.content){let b;if("tool-approval-response"===a.type)continue;let d=a.output;switch(d.type){case"text":case"error-text":b=d.value;break;case"execution-denied":b=null!=(l=d.reason)?l:"tool execution denied";break;case"json":case"error-json":b=JSON.stringify(d.value);break;case"content":for(let a of(b=[],d.value))switch(a.type){case"text":b.push({type:"input_text",text:a.text});break;case"file":"image"===(0,c.getTopLevelMediaType)(a.mediaType)&&("data"===a.data.type||"url"===a.data.type)&&b.push({type:"input_image",image_url:"url"===a.data.type?a.data.url.toString():`data:${(0,c.resolveFullMediaType)({part:a})};base64,${(0,c.convertToBase64)(a.data.data)}`})}break;default:b=""}m.push({type:"function_call_output",call_id:a.toolCallId,output:b})}break;default:n.push({type:"other",message:"unsupported message role"})}return{input:m,inputWarnings:n}}function t(a){var b,c,d,e;let f=null!=(c=null==(b=a.input_tokens_details)?void 0:b.cached_tokens)?c:0,g=null!=(e=null==(d=a.output_tokens_details)?void 0:d.reasoning_tokens)?e:0,h=f<=a.input_tokens;return{inputTokens:{total:h?a.input_tokens:a.input_tokens+f,noCache:h?a.input_tokens-f:a.input_tokens,cacheRead:f,cacheWrite:void 0},outputTokens:{total:a.output_tokens,text:a.output_tokens-g,reasoning:g},raw:a}}function u(a){switch(a){case"stop":case"completed":return"stop";case"length":case"max_output_tokens":return"length";case"tool_calls":case"function_call":return"tool-calls";case"content_filter":return"content-filter";default:return"other"}}var v=e.z.union([e.z.object({type:e.z.literal("url_citation"),url:e.z.string(),title:e.z.string().optional()}),e.z.object({type:e.z.string()})]),w=e.z.object({type:e.z.string(),text:e.z.string().optional(),logprobs:e.z.array(e.z.any()).optional(),annotations:e.z.array(v).optional()}),x=e.z.object({type:e.z.string(),text:e.z.string()}),y=e.z.object({name:e.z.string().optional(),arguments:e.z.string().optional(),input:e.z.string().optional(),call_id:e.z.string().optional(),id:e.z.string(),status:e.z.string(),action:e.z.any().optional()}),z=e.z.object({type:e.z.literal("url"),url:e.z.string()}),A=e.z.discriminatedUnion("type",[e.z.object({type:e.z.literal("search"),query:e.z.string().nullish(),queries:e.z.array(e.z.string()).nullish(),sources:e.z.array(e.z.unknown()).nullish()}),e.z.object({type:e.z.literal("open_page"),url:e.z.string().nullish(),sources:e.z.array(e.z.unknown()).nullish()}),e.z.object({type:e.z.literal("find_in_page"),url:e.z.string().nullish(),pattern:e.z.string().nullish(),sources:e.z.array(e.z.unknown()).nullish()})]),B=e.z.object({name:e.z.string().optional(),arguments:e.z.string().optional(),output:e.z.string().optional(),error:e.z.string().optional(),id:e.z.string(),status:e.z.string(),server_label:e.z.string().optional()}),C=e.z.discriminatedUnion("type",[e.z.object({type:e.z.literal("web_search_call"),...y.shape}),e.z.object({type:e.z.literal("x_search_call"),...y.shape}),e.z.object({type:e.z.literal("code_interpreter_call"),...y.shape}),e.z.object({type:e.z.literal("code_execution_call"),...y.shape}),e.z.object({type:e.z.literal("view_image_call"),...y.shape}),e.z.object({type:e.z.literal("view_x_video_call"),...y.shape}),e.z.object({type:e.z.literal("file_search_call"),id:e.z.string(),status:e.z.string(),queries:e.z.array(e.z.string()).optional(),results:e.z.array(e.z.object({file_id:e.z.string(),filename:e.z.string(),score:e.z.number(),text:e.z.string()})).nullish()}),e.z.object({type:e.z.literal("image_generation_call"),id:e.z.string(),status:e.z.string(),prompt:e.z.string().nullish(),result:e.z.string().nullish()}),e.z.object({type:e.z.literal("custom_tool_call"),...y.shape}),e.z.object({type:e.z.literal("mcp_call"),...B.shape}),e.z.object({type:e.z.literal("message"),role:e.z.string(),content:e.z.array(w),id:e.z.string(),status:e.z.string()}),e.z.object({type:e.z.literal("function_call"),name:e.z.string(),arguments:e.z.string(),call_id:e.z.string(),id:e.z.string()}),e.z.object({type:e.z.literal("reasoning"),id:e.z.string(),summary:e.z.array(x),content:e.z.array(e.z.object({type:e.z.string(),text:e.z.string()})).nullish(),status:e.z.string(),encrypted_content:e.z.string().nullish()})]),D=e.z.object({input_tokens:e.z.number(),output_tokens:e.z.number(),total_tokens:e.z.number().optional(),input_tokens_details:e.z.object({cached_tokens:e.z.number().optional()}).catchall(e.z.json()).optional(),output_tokens_details:e.z.object({reasoning_tokens:e.z.number().optional()}).catchall(e.z.json()).optional(),num_sources_used:e.z.number().optional(),num_server_side_tools_used:e.z.number().optional(),cost_in_usd_ticks:e.z.number().nullish()}).catchall(e.z.json()),E=e.z.object({id:e.z.string().nullish(),created_at:e.z.number().nullish(),model:e.z.string().nullish(),object:e.z.literal("response"),output:e.z.array(C),usage:D.nullish(),status:e.z.string(),service_tier:e.z.string().nullish()}),F=e.z.union([e.z.object({type:e.z.literal("response.created"),response:E.partial({usage:!0,status:!0})}),e.z.object({type:e.z.literal("response.in_progress"),response:E.partial({usage:!0,status:!0})}),e.z.object({type:e.z.literal("response.output_item.added"),item:C,output_index:e.z.number()}),e.z.object({type:e.z.literal("response.output_item.done"),item:C,output_index:e.z.number()}),e.z.object({type:e.z.literal("response.content_part.added"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),part:w}),e.z.object({type:e.z.literal("response.content_part.done"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),part:w}),e.z.object({type:e.z.literal("response.output_text.delta"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),delta:e.z.string(),logprobs:e.z.array(e.z.any()).optional()}),e.z.object({type:e.z.literal("response.output_text.done"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),text:e.z.string(),logprobs:e.z.array(e.z.any()).optional(),annotations:e.z.array(v).optional()}),e.z.object({type:e.z.literal("response.output_text.annotation.added"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),annotation_index:e.z.number(),annotation:v}),e.z.object({type:e.z.literal("response.reasoning_summary_part.added"),item_id:e.z.string(),output_index:e.z.number(),summary_index:e.z.number(),part:x}),e.z.object({type:e.z.literal("response.reasoning_summary_part.done"),item_id:e.z.string(),output_index:e.z.number(),summary_index:e.z.number(),part:x}),e.z.object({type:e.z.literal("response.reasoning_summary_text.delta"),item_id:e.z.string(),output_index:e.z.number(),summary_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.reasoning_summary_text.done"),item_id:e.z.string(),output_index:e.z.number(),summary_index:e.z.number(),text:e.z.string()}),e.z.object({type:e.z.literal("response.reasoning_text.delta"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.reasoning_text.done"),item_id:e.z.string(),output_index:e.z.number(),content_index:e.z.number(),text:e.z.string()}),e.z.object({type:e.z.literal("response.web_search_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.web_search_call.searching"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.web_search_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.x_search_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.x_search_call.searching"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.x_search_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.file_search_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.file_search_call.searching"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.file_search_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.image_generation_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.image_generation_call.generating"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.image_generation_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_execution_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_execution_call.executing"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_execution_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_interpreter_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_interpreter_call.executing"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_interpreter_call.interpreting"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_interpreter_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.code_interpreter_call_code.delta"),item_id:e.z.string(),output_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.code_interpreter_call_code.done"),item_id:e.z.string(),output_index:e.z.number(),code:e.z.string()}),e.z.object({type:e.z.literal("response.custom_tool_call_input.delta"),item_id:e.z.string(),output_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.custom_tool_call_input.done"),item_id:e.z.string(),output_index:e.z.number(),input:e.z.string()}),e.z.object({type:e.z.literal("response.function_call_arguments.delta"),item_id:e.z.string(),output_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.function_call_arguments.done"),item_id:e.z.string(),output_index:e.z.number(),arguments:e.z.string()}),e.z.object({type:e.z.literal("response.mcp_call.in_progress"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.mcp_call.executing"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.mcp_call.completed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.mcp_call.failed"),item_id:e.z.string(),output_index:e.z.number()}),e.z.object({type:e.z.literal("response.mcp_call_arguments.delta"),item_id:e.z.string(),output_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.mcp_call_arguments.done"),item_id:e.z.string(),output_index:e.z.number(),arguments:e.z.string().optional()}),e.z.object({type:e.z.literal("response.mcp_call_output.delta"),item_id:e.z.string(),output_index:e.z.number(),delta:e.z.string()}),e.z.object({type:e.z.literal("response.mcp_call_output.done"),item_id:e.z.string(),output_index:e.z.number(),output:e.z.string().optional()}),e.z.object({type:e.z.literal("response.incomplete"),response:e.z.object({incomplete_details:e.z.object({reason:e.z.string()}).nullish(),usage:D.nullish(),service_tier:e.z.string().nullish()})}),e.z.object({type:e.z.literal("response.failed"),response:e.z.object({error:e.z.object({code:e.z.string().nullish(),message:e.z.string()}).nullish(),incomplete_details:e.z.object({reason:e.z.string()}).nullish(),usage:D.nullish()})}),e.z.object({type:e.z.literal("error"),code:e.z.string().nullish(),message:e.z.string(),param:e.z.string().nullish()}),e.z.object({type:e.z.literal("response.done"),response:E}),e.z.object({type:e.z.literal("response.completed"),response:E})]),G=e.z.object({reasoningEffort:e.z.enum(["none","low","medium","high","xhigh"]).optional(),reasoningSummary:e.z.enum(["auto","concise","detailed"]).optional(),logprobs:e.z.boolean().optional(),topLogprobs:e.z.number().int().min(0).max(8).optional(),serviceTier:e.z.enum(["default","priority"]).optional(),store:e.z.boolean().optional(),previousResponseId:e.z.string().optional(),include:e.z.array(e.z.enum(["file_search_call.results"])).nullish()}),H=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({vectorStoreIds:e.z.array(e.z.string()),maxNumResults:e.z.number().optional()}))),I=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({queries:e.z.array(e.z.string()),results:e.z.array(e.z.object({fileId:e.z.string(),filename:e.z.string(),score:e.z.number().min(0).max(1),text:e.z.string()})).nullable()}))),J=(0,c.createProviderExecutedToolFactory)({id:"xai.file_search",inputSchema:(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({}))),outputSchema:I}),K=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({action:e.z.enum(["auto","generate","edit"]).optional()}))),L=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({}))),M=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({result:e.z.string(),prompt:e.z.string().optional()}))),N=(0,c.createProviderExecutedToolFactory)({id:"xai.image_generation",inputSchema:L,outputSchema:M}),O=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({serverUrl:e.z.string().describe("The URL of the MCP server"),serverLabel:e.z.string().optional().describe("A label for the MCP server"),serverDescription:e.z.string().optional().describe("Description of the MCP server"),allowedTools:e.z.array(e.z.string()).optional().describe("List of allowed tool names"),headers:e.z.record(e.z.string(),e.z.string()).optional().describe("Custom headers to send"),authorization:e.z.string().optional().describe("Authorization header value")}))),P=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({name:e.z.string(),arguments:e.z.string(),result:e.z.unknown()}))),Q=(0,c.createProviderExecutedToolFactory)({id:"xai.mcp",inputSchema:(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({}))),outputSchema:P}),R=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({allowedDomains:e.z.array(e.z.string()).max(5).optional(),excludedDomains:e.z.array(e.z.string()).max(5).optional(),enableImageSearch:e.z.boolean().optional(),enableImageUnderstanding:e.z.boolean().optional()}))),S=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({action:e.z.discriminatedUnion("type",[e.z.object({type:e.z.literal("search"),query:e.z.string().optional(),queries:e.z.array(e.z.string()).optional()}),e.z.object({type:e.z.literal("openPage"),url:e.z.string().nullish()}),e.z.object({type:e.z.literal("findInPage"),url:e.z.string().nullish(),pattern:e.z.string().nullish()})]).optional(),sources:e.z.array(e.z.object({type:e.z.literal("url"),url:e.z.string()})).optional()}))),T=(0,c.createProviderExecutedToolFactory)({id:"xai.web_search",inputSchema:(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({}))),outputSchema:S}),U=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({allowedXHandles:e.z.array(e.z.string()).max(10).optional(),excludedXHandles:e.z.array(e.z.string()).max(10).optional(),fromDate:e.z.string().optional(),toDate:e.z.string().optional(),enableImageUnderstanding:e.z.boolean().optional(),enableVideoUnderstanding:e.z.boolean().optional()}))),V=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({query:e.z.string(),posts:e.z.array(e.z.object({author:e.z.string(),text:e.z.string(),url:e.z.string(),likes:e.z.number()}))}))),W=(0,c.createProviderExecutedToolFactory)({id:"xai.x_search",inputSchema:(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({}))),outputSchema:V});async function X({tools:a,toolChoice:d}){let e=(null==a?void 0:a.length)?a:void 0,f=[];if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:f};let g=[],h=new Map;for(let a of e)if(h.set(a.name,a),"provider"===a.type)switch(a.id){case"xai.web_search":{let b=await (0,c.validateTypes)({value:a.args,schema:R});g.push({type:"web_search",allowed_domains:b.allowedDomains,excluded_domains:b.excludedDomains,enable_image_search:b.enableImageSearch,enable_image_understanding:b.enableImageUnderstanding});break}case"xai.x_search":{let b=await (0,c.validateTypes)({value:a.args,schema:U});g.push({type:"x_search",allowed_x_handles:b.allowedXHandles,excluded_x_handles:b.excludedXHandles,from_date:b.fromDate,to_date:b.toDate,enable_image_understanding:b.enableImageUnderstanding,enable_video_understanding:b.enableVideoUnderstanding});break}case"xai.code_execution":g.push({type:"code_interpreter"});break;case"xai.view_image":g.push({type:"view_image"});break;case"xai.view_x_video":g.push({type:"view_x_video"});break;case"xai.image_generation":{let b=await (0,c.validateTypes)({value:a.args,schema:K});g.push({type:"image_generation",action:b.action});break}case"xai.file_search":{let b=await (0,c.validateTypes)({value:a.args,schema:H});g.push({type:"file_search",vector_store_ids:b.vectorStoreIds,max_num_results:b.maxNumResults});break}case"xai.mcp":{let b=await (0,c.validateTypes)({value:a.args,schema:O});g.push({type:"mcp",server_url:b.serverUrl,server_label:b.serverLabel,server_description:b.serverDescription,allowed_tools:b.allowedTools,headers:b.headers,authorization:b.authorization});break}default:f.push({type:"unsupported",feature:`provider-defined tool ${a.name}`})}else g.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,...null!=a.strict?{strict:a.strict}:{}});if(null==d)return{tools:g,toolChoice:void 0,toolWarnings:f};let i=d.type;switch(i){case"auto":case"none":return{tools:g,toolChoice:i,toolWarnings:f};case"required":return{tools:g,toolChoice:"required",toolWarnings:f};case"tool":{let a=h.get(d.toolName);if(null==a)return{tools:g,toolChoice:void 0,toolWarnings:f};if("provider"===a.type)return f.push({type:"unsupported",feature:`toolChoice for server-side tool "${a.name}"`}),{tools:g,toolChoice:void 0,toolWarnings:f};return{tools:g,toolChoice:{type:"function",name:a.name},toolWarnings:f}}default:throw new b.UnsupportedFunctionalityError({functionality:`tool choice type: ${i}`})}}function Y({message:a,code:b,eventType:d,data:e}){var f,g;let h,i="number"==typeof(h="string"==typeof(f=b)&&/^\d{3}$/.test(f)?Number(f):f)&&Number.isInteger(h)&&h>=400&&h<=599?h:void 0;return(0,c.createProviderStreamError)({message:a,type:d,code:null!=b?b:void 0,...null!=i?{statusCode:i,isRetryable:408===(g=i)||409===g||429===g||g>=500}:function(a){switch(a){case"rate_limit_exceeded":case"rate_limit_error":return{statusCode:429,isRetryable:!0};case"insufficient_quota":return{statusCode:429,isRetryable:!1};case"api_error":case"internal_server_error":case"server_error":return{statusCode:500,isRetryable:!0};case"overloaded_error":case"service_unavailable":return{statusCode:503,isRetryable:!0};case"timeout":case"timeout_error":return{statusCode:504,isRetryable:!0};case"authentication_error":case"invalid_api_key":return{statusCode:401,isRetryable:!1};case"permission_error":return{statusCode:403,isRetryable:!1};case"not_found_error":case"model_not_found":return{statusCode:404,isRetryable:!1};case"bad_request":case"context_length_exceeded":case"invalid_request_error":return{statusCode:400,isRetryable:!1};default:return{}}}(b),data:e})}var Z={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/],"text/*":[/^https?:\/\/.*$/]},$=class a{constructor(a,b){this.specificationVersion="v4",this.supportedUrls=Z,this.modelId=a,this.config=b}static[d.WORKFLOW_SERIALIZE](a){return(0,c.serializeModelOptions)({modelId:a.modelId,config:a.config})}static[d.WORKFLOW_DESERIALIZE](b){return new a(b.modelId,b.config)}get provider(){return this.config.provider}static async prepareRequest({modelId:a,options:{prompt:b,maxOutputTokens:d,temperature:e,topP:f,topK:g,frequencyPenalty:h,presencePenalty:i,stopSequences:j,seed:k,responseFormat:l,providerOptions:m,tools:n,toolChoice:o,reasoning:p}}){var r,t,u,v,w,x,y,z,A;let B=[],C=null!=(r=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:m,schema:G}))?r:{};null!=g&&B.push({type:"unsupported",feature:"topK"}),null!=h&&B.push({type:"unsupported",feature:"frequencyPenalty"}),null!=i&&B.push({type:"unsupported",feature:"presencePenalty"}),null!=j&&B.push({type:"unsupported",feature:"stopSequences"});let D=null==(t=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.web_search"===a.id))?void 0:t.name,E=null==(u=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.x_search"===a.id))?void 0:u.name,F=null==(v=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.code_execution"===a.id))?void 0:v.name,H=null==(w=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.mcp"===a.id))?void 0:w.name,I=null==(x=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.file_search"===a.id))?void 0:x.name,J=null==(y=null==n?void 0:n.find(a=>"provider"===a.type&&"xai.image_generation"===a.id))?void 0:y.name,{input:K,inputWarnings:L}=await s({prompt:b,store:null==(z=C.store)||z});B.push(...L);let{tools:M,toolChoice:N,toolWarnings:O}=await X({tools:n,toolChoice:o});B.push(...O);let P=C.include?[...C.include]:void 0;!1===C.store&&(P=null==P?["reasoning.encrypted_content"]:[...P,"reasoning.encrypted_content"]);let Q=C.reasoningEffort;null==Q&&(0,c.isCustomReasoning)(p)&&(q.test(a)?B.push({type:"unsupported",feature:"reasoning",details:`reasoning "${p}" is not supported by this model.`}):Q="none"===p?"none":(0,c.mapReasoningToProviderEffort)({reasoning:p,effortMap:{minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"grok-4.6"===a?"xhigh":"high"},warnings:B}));let R={model:a,input:K,logprobs:!0===C.logprobs||null!=C.topLogprobs||void 0,top_logprobs:C.topLogprobs,max_output_tokens:d,temperature:e,top_p:f,seed:k,...(null==l?void 0:l.type)==="json"&&{text:{format:null!=l.schema?{type:"json_schema",strict:!0,name:null!=(A=l.name)?A:"response",description:l.description,schema:l.schema}:{type:"json_object"}}},...(null!=Q||null!=C.reasoningSummary)&&{reasoning:{...null!=Q&&{effort:Q},...null!=C.reasoningSummary&&{summary:C.reasoningSummary}}},...!1===C.store&&{store:C.store},...null!=P&&{include:P},...null!=C.previousResponseId&&{previous_response_id:C.previousResponseId},...null!=C.serviceTier&&{service_tier:C.serviceTier}};return M&&M.length>0&&(R.tools=M),null!=N&&(R.tool_choice=N),{args:R,warnings:B,webSearchToolName:D,xSearchToolName:E,codeExecutionToolName:F,mcpToolName:H,fileSearchToolName:I,imageGenerationToolName:J}}getArgs(b){return a.prepareRequest({modelId:this.modelId,options:b})}async doGenerate(a){var b,d,e,f,g,h,i,k,l,m,o,p,q,r,s,v,w,x;let{args:y,warnings:z,webSearchToolName:A,xSearchToolName:B,codeExecutionToolName:C,mcpToolName:D,fileSearchToolName:F,imageGenerationToolName:G}=await this.getArgs(a),{responseHeaders:H,value:I,rawValue:J}=await (0,c.postJsonToApi)({url:`${null!=(b=this.config.baseURL)?b:"https://api.x.ai/v1"}/responses`,headers:(0,c.combineHeaders)(null==(e=(d=this.config).headers)?void 0:e.call(d),a.headers),body:y,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(E),abortSignal:a.abortSignal,fetch:this.config.fetch}),K=[],L=!1,M=["web_search","web_search_with_snippets","browse_page"],N=["x_user_search","x_keyword_search","x_semantic_search","x_thread_fetch"];for(let a of I.output){if("file_search_call"===a.type){let b=null!=F?F:"file_search";K.push({type:"tool-call",toolCallId:a.id,toolName:b,input:"",providerExecuted:!0}),K.push({type:"tool-result",toolCallId:a.id,toolName:b,result:{queries:null!=(f=a.queries)?f:[],results:null!=(h=null==(g=a.results)?void 0:g.map(a=>({fileId:a.file_id,filename:a.filename,score:a.score,text:a.text})))?h:null}});continue}if("image_generation_call"===a.type){let b=null!=G?G:"image_generation";K.push({type:"tool-call",toolCallId:a.id,toolName:b,input:"{}",providerExecuted:!0}),null!=a.result?K.push({type:"tool-result",toolCallId:a.id,toolName:b,result:{result:a.result,...null!=a.prompt&&{prompt:a.prompt}}}):K.push({type:"tool-result",toolCallId:a.id,toolName:b,isError:!0,result:`Image generation failed (status: ${a.status}).`});continue}if("web_search_call"===a.type||"x_search_call"===a.type||"code_interpreter_call"===a.type||"code_execution_call"===a.type||"view_image_call"===a.type||"view_x_video_call"===a.type||"custom_tool_call"===a.type||"mcp_call"===a.type){let b=null!=(i=a.name)?i:"";M.includes(null!=(k=a.name)?k:"")||"web_search_call"===a.type?b=null!=A?A:"web_search":N.includes(null!=(l=a.name)?l:"")||"x_search_call"===a.type?b=null!=B?B:"x_search":"code_execution"===a.name||"code_interpreter_call"===a.type||"code_execution_call"===a.type?b=null!=C?C:"code_execution":"mcp_call"===a.type&&(b=null!=(m=null!=D?D:a.name)?m:"mcp");let c="custom_tool_call"===a.type?null!=(o=a.input)?o:"":"mcp_call"===a.type?null!=(p=a.arguments)?p:"":null!=(q=a.arguments)?q:"";K.push({type:"tool-call",toolCallId:a.id,toolName:b,input:c,providerExecuted:!0}),"web_search_call"===a.type&&K.push({type:"tool-result",toolCallId:a.id,toolName:b,result:_(a.action)});continue}switch(a.type){case"message":for(let b of a.content)if(b.text&&K.push({type:"text",text:b.text}),b.annotations)for(let a of b.annotations)"url_citation"===a.type&&"url"in a&&K.push({type:"source",sourceType:"url",id:this.config.generateId(),url:a.url,title:null!=(r=a.title)?r:a.url});break;case"function_call":L=!0,K.push({type:"tool-call",toolCallId:a.call_id,toolName:a.name,input:a.arguments});break;case"reasoning":{let b=(a.summary.length>0?a.summary.map(a=>a.text):(null!=(s=a.content)?s:[]).map(a=>a.text)).filter(a=>a&&a.length>0).join("");if(b||a.encrypted_content){let c=a.encrypted_content||a.id;K.push({type:"reasoning",text:b,...c&&{providerMetadata:{xai:{...a.encrypted_content&&{reasoningEncryptedContent:a.encrypted_content},...a.id&&{itemId:a.id}}}}})}}}}return{content:K,finishReason:{unified:L?"tool-calls":u(I.status),raw:null!=(v=I.status)?v:void 0},usage:I.usage?t(I.usage):{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...((null==(w=I.usage)?void 0:w.cost_in_usd_ticks)!=null||null!=I.service_tier)&&{providerMetadata:{xai:{...(null==(x=I.usage)?void 0:x.cost_in_usd_ticks)!=null&&{costInUsdTicks:I.usage.cost_in_usd_ticks},...null!=I.service_tier&&{serviceTier:I.service_tier}}}},request:{body:y},response:{...n(I),headers:H,body:J},warnings:z}}async doStream(a){var b,d,e;let f,g,h,{args:i,warnings:k,webSearchToolName:l,xSearchToolName:m,codeExecutionToolName:o,mcpToolName:p,fileSearchToolName:q,imageGenerationToolName:r}=await this.getArgs(a),s={...i,stream:!0},{responseHeaders:v,value:w}=await (0,c.postJsonToApi)({url:`${null!=(b=this.config.baseURL)?b:"https://api.x.ai/v1"}/responses`,headers:(0,c.combineHeaders)(null==(e=(d=this.config).headers)?void 0:e.call(d),a.headers),body:s,failedResponseHandler:j,successfulResponseHandler:(0,c.createEventSourceResponseHandler)(F),abortSignal:a.abortSignal,fetch:this.config.fetch}),x={unified:"other",raw:void 0},y=!1,z=!0,A={},B=new Set,C={},D={},E=this;return{stream:w.pipeThrough(new TransformStream({start(a){a.enqueue({type:"stream-start",warnings:k})},transform(b,c){var d,e,i,j,k,s,v,w,F,G,H,I,J,K,L,M,N;if(a.includeRawChunks&&c.enqueue({type:"raw",rawValue:b.rawValue}),!b.success)return void c.enqueue({type:"error",error:b.error});let O=b.value;if("response.created"===O.type||"response.in_progress"===O.type){z&&(c.enqueue({type:"response-metadata",...n(O.response)}),z=!1);return}if("response.reasoning_summary_part.added"===O.type){let a=`reasoning-${O.item_id}`;null==D[O.item_id]&&(D[O.item_id]={},c.enqueue({type:"reasoning-start",id:a,providerMetadata:{xai:{itemId:O.item_id}}}))}if("response.reasoning_summary_text.delta"===O.type){let a=`reasoning-${O.item_id}`;c.enqueue({type:"reasoning-delta",id:a,delta:O.delta,providerMetadata:{xai:{itemId:O.item_id}}});return}if("response.reasoning_summary_text.done"===O.type)return;if("response.reasoning_text.delta"===O.type){let a=`reasoning-${O.item_id}`;null==D[O.item_id]&&(D[O.item_id]={},c.enqueue({type:"reasoning-start",id:a,providerMetadata:{xai:{itemId:O.item_id}}})),c.enqueue({type:"reasoning-delta",id:a,delta:O.delta,providerMetadata:{xai:{itemId:O.item_id}}});return}if("response.reasoning_text.done"!==O.type){if("response.output_text.delta"===O.type){let a=`text-${O.item_id}`;null==A[a]&&(A[a]={type:"text"},c.enqueue({type:"text-start",id:a})),c.enqueue({type:"text-delta",id:a,delta:O.delta});return}if("response.output_text.done"===O.type){if(O.annotations)for(let a of O.annotations)"url_citation"===a.type&&"url"in a&&c.enqueue({type:"source",sourceType:"url",id:E.config.generateId(),url:a.url,title:null!=(d=a.title)?d:a.url});return}if("response.output_text.annotation.added"===O.type){let a=O.annotation;"url_citation"===a.type&&"url"in a&&c.enqueue({type:"source",sourceType:"url",id:E.config.generateId(),url:a.url,title:null!=(e=a.title)?e:a.url});return}if("response.done"===O.type||"response.completed"===O.type||"response.incomplete"===O.type){let a=O.response;if(a.usage&&(f=t(a.usage),g=null!=(i=a.usage.cost_in_usd_ticks)?i:void 0),h=null!=(j=a.service_tier)?j:void 0,"response.incomplete"===O.type){let b="incomplete_details"in a?null==(k=a.incomplete_details)?void 0:k.reason:void 0;x={unified:b?u(b):"other",raw:null!=b?b:"incomplete"}}else"status"in a&&a.status&&(x={unified:y?"tool-calls":u(a.status),raw:a.status});return}if("response.failed"===O.type){let a=null==(s=O.response.incomplete_details)?void 0:s.reason;x={unified:a?u(a):"error",raw:null!=a?a:"error"},O.response.usage&&(f=t(O.response.usage)),null!=O.response.error&&c.enqueue({type:"error",error:Y({message:O.response.error.message,code:O.response.error.code,eventType:O.type,data:O})});return}if("error"===O.type)return void c.enqueue({type:"error",error:Y({message:O.message,code:O.code,eventType:O.type,data:O})});if("response.custom_tool_call_input.delta"!==O.type&&"response.custom_tool_call_input.done"!==O.type){if("response.function_call_arguments.delta"===O.type){let a=C[O.output_index];null!=a&&c.enqueue({type:"tool-input-delta",id:a.toolCallId,delta:O.delta});return}if("response.function_call_arguments.done"!==O.type){if("response.image_generation_call.in_progress"===O.type||"response.image_generation_call.generating"===O.type||"response.image_generation_call.completed"===O.type){if(!B.has(O.item_id)){B.add(O.item_id);let a=null!=r?r:"image_generation";c.enqueue({type:"tool-input-start",id:O.item_id,toolName:a}),c.enqueue({type:"tool-input-delta",id:O.item_id,delta:"{}"}),c.enqueue({type:"tool-input-end",id:O.item_id}),c.enqueue({type:"tool-call",toolCallId:O.item_id,toolName:a,input:"{}",providerExecuted:!0})}return}if("response.output_item.added"===O.type||"response.output_item.done"===O.type){let a=O.item;if("reasoning"===a.type){if("response.output_item.done"===O.type){let b=`reasoning-${a.id}`;a.id in D||(D[a.id]={},c.enqueue({type:"reasoning-start",id:b,providerMetadata:{xai:{...a.id&&{itemId:a.id}}}})),c.enqueue({type:"reasoning-end",id:b,providerMetadata:{xai:{...a.encrypted_content&&{reasoningEncryptedContent:a.encrypted_content},...a.id&&{itemId:a.id}}}}),delete D[a.id]}return}if("file_search_call"===a.type){let b=null!=q?q:"file_search";B.has(a.id)||(B.add(a.id),c.enqueue({type:"tool-input-start",id:a.id,toolName:b}),c.enqueue({type:"tool-input-delta",id:a.id,delta:""}),c.enqueue({type:"tool-input-end",id:a.id}),c.enqueue({type:"tool-call",toolCallId:a.id,toolName:b,input:"",providerExecuted:!0})),"response.output_item.done"===O.type&&c.enqueue({type:"tool-result",toolCallId:a.id,toolName:b,result:{queries:null!=(v=a.queries)?v:[],results:null!=(F=null==(w=a.results)?void 0:w.map(a=>({fileId:a.file_id,filename:a.filename,score:a.score,text:a.text})))?F:null}});return}if("image_generation_call"===a.type){let b=null!=r?r:"image_generation";B.has(a.id)||(B.add(a.id),c.enqueue({type:"tool-input-start",id:a.id,toolName:b}),c.enqueue({type:"tool-input-delta",id:a.id,delta:"{}"}),c.enqueue({type:"tool-input-end",id:a.id}),c.enqueue({type:"tool-call",toolCallId:a.id,toolName:b,input:"{}",providerExecuted:!0})),"response.output_item.done"===O.type&&(null!=a.result?c.enqueue({type:"tool-result",toolCallId:a.id,toolName:b,result:{result:a.result,...null!=a.prompt&&{prompt:a.prompt}}}):c.enqueue({type:"tool-result",toolCallId:a.id,toolName:b,isError:!0,result:`Image generation failed (status: ${a.status}).`}));return}if("web_search_call"===a.type||"x_search_call"===a.type||"code_interpreter_call"===a.type||"code_execution_call"===a.type||"view_image_call"===a.type||"view_x_video_call"===a.type||"custom_tool_call"===a.type||"mcp_call"===a.type){let b=null!=(G=a.name)?G:"";["web_search","web_search_with_snippets","browse_page"].includes(null!=(H=a.name)?H:"")||"web_search_call"===a.type?b=null!=l?l:"web_search":["x_user_search","x_keyword_search","x_semantic_search","x_thread_fetch"].includes(null!=(I=a.name)?I:"")||"x_search_call"===a.type?b=null!=m?m:"x_search":"code_execution"===a.name||"code_interpreter_call"===a.type||"code_execution_call"===a.type?b=null!=o?o:"code_execution":"mcp_call"===a.type&&(b=null!=(J=null!=p?p:a.name)?J:"mcp");let d="custom_tool_call"===a.type?null!=(K=a.input)?K:"":"mcp_call"===a.type?null!=(L=a.arguments)?L:"":null!=(M=a.arguments)?M:"";("custom_tool_call"===a.type?"response.output_item.done"!==O.type:B.has(a.id))||B.has(a.id)||(B.add(a.id),c.enqueue({type:"tool-input-start",id:a.id,toolName:b}),c.enqueue({type:"tool-input-delta",id:a.id,delta:d}),c.enqueue({type:"tool-input-end",id:a.id}),c.enqueue({type:"tool-call",toolCallId:a.id,toolName:b,input:d,providerExecuted:!0})),"response.output_item.done"===O.type&&c.enqueue({type:"tool-result",toolCallId:a.id,toolName:b,result:"web_search_call"===a.type?_(a.action):{}});return}if("message"===a.type)for(let b of a.content){if(b.text&&b.text.length>0){let d=`text-${a.id}`;null==A[d]&&(A[d]={type:"text"},c.enqueue({type:"text-start",id:d}),c.enqueue({type:"text-delta",id:d,delta:b.text}))}if(b.annotations)for(let a of b.annotations)"url_citation"===a.type&&"url"in a&&c.enqueue({type:"source",sourceType:"url",id:E.config.generateId(),url:a.url,title:null!=(N=a.title)?N:a.url})}else"function_call"===a.type&&("response.output_item.added"===O.type?(C[O.output_index]={toolName:a.name,toolCallId:a.call_id},c.enqueue({type:"tool-input-start",id:a.call_id,toolName:a.name})):"response.output_item.done"===O.type&&(y=!0,C[O.output_index]=void 0,c.enqueue({type:"tool-input-end",id:a.call_id}),c.enqueue({type:"tool-call",toolCallId:a.call_id,toolName:a.name,input:a.arguments})))}}}}},flush(a){for(let[b,c]of Object.entries(A))"text"===c.type&&a.enqueue({type:"text-end",id:b});a.enqueue({type:"finish",finishReason:x,usage:null!=f?f:{inputTokens:{total:0,noCache:0,cacheRead:0,cacheWrite:0},outputTokens:{total:0,text:0,reasoning:0}},...(null!=g||null!=h)&&{providerMetadata:{xai:{...null!=g&&{costInUsdTicks:g},...null!=h&&{serviceTier:h}}}}})}})),request:{body:s},response:{headers:v}}}};function _(a){var b;let c=A.safeParse(a);if(!c.success)return{};let d=c.data,e=null==(b=d.sources)?void 0:b.flatMap(a=>{let b=z.safeParse(a);return b.success?[b.data]:[]}),f=null!=e&&e.length>0?{sources:e}:{};switch(d.type){case"search":return{action:{type:"search",...null!=d.query&&{query:d.query},...null!=d.queries&&{queries:d.queries}},...f};case"open_page":return{action:{type:"openPage",url:d.url},...f};case"find_in_page":return{action:{type:"findInPage",url:d.url,pattern:d.pattern},...f}}}var aa=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({inputFileExpiresAfter:e.z.number().int().min(3600).max(2592e3).optional()}))),ab=e.z.object({data:e.z.array(e.z.object({url:e.z.string().nullish(),b64_json:e.z.string().nullish(),revised_prompt:e.z.string().nullish(),respect_moderation:e.z.boolean().nullish()})),usage:e.z.object({cost_in_usd_ticks:e.z.number().nullish()}).nullish()}),ac=()=>e.z.object({batch_id:e.z.string(),name:e.z.string().nullish(),create_time:e.z.string().nullish(),expire_time:e.z.string().nullish(),cancel_time:e.z.string().nullish(),cancel_by_xai_message:e.z.string().nullish(),state:e.z.object({num_requests:e.z.number().nullish(),num_pending:e.z.number().nullish(),num_success:e.z.number().nullish(),num_error:e.z.number().nullish(),num_cancelled:e.z.number().nullish()}).nullish()}),ad=(0,c.lazySchema)(()=>(0,c.zodSchema)(ac())),ae=e.z.object({code:e.z.union([e.z.string(),e.z.number()]).nullish(),message:e.z.string().nullish()}),af=e.z.object({batch_request_id:e.z.string(),batch_result:e.z.object({response:e.z.object({chat_get_completion:e.z.unknown().nullish(),image_generation:e.z.unknown().nullish()}).nullish(),error:ae.nullish()}).nullish(),error_message:e.z.string().nullish()}),ag=e.z.object({id:e.z.string().nullish(),created:e.z.number().nullish(),model:e.z.string().nullish(),choices:e.z.array(e.z.object({message:e.z.object({role:e.z.enum(["assistant","tool"]),content:e.z.string().nullish(),reasoning_content:e.z.string().nullish(),tool_calls:e.z.array(e.z.object({id:e.z.string(),type:e.z.literal("function"),function:e.z.object({name:e.z.string(),arguments:e.z.string()})})).nullish()}),index:e.z.number(),finish_reason:e.z.string().nullish()})).nullish(),usage:e.z.object({prompt_tokens:e.z.number(),completion_tokens:e.z.number(),total_tokens:e.z.number(),cost_in_usd_ticks:e.z.number().nullish(),prompt_tokens_details:e.z.object({cached_tokens:e.z.number().nullish()}).nullish(),completion_tokens_details:e.z.object({reasoning_tokens:e.z.number().nullish()}).nullish()}).nullish(),citations:e.z.array(e.z.string().url()).nullish(),service_tier:e.z.string().nullish(),code:e.z.string().nullish(),error:e.z.string().nullish()}),ah=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({results:e.z.array(af),pagination_token:e.z.string().nullish()}))),ai=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({batches:e.z.array(ac()),pagination_token:e.z.string().nullish()}))),aj=class{constructor(a){this.options=a,this.specificationVersion="v4",this.supportedUrls=Z,this.provider=a.provider}async doStartBatch(a){var d,e;for(let c of a.requests){let a=c.type;if("text"!==a&&"image"!==a)throw new b.UnsupportedFunctionalityError({functionality:`batch request type: ${a}`,message:`The xAI Batch API does not support batch requests with type "${a}".`})}let f=[],g=null==a.webhookUrl?[]:[{warning:{type:"unsupported",feature:"webhookUrl",details:"The xAI Batch API does not support per-batch webhook URLs."}}],h=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:a.providerOptions,schema:aa});for(let b of a.requests){let a=await this.prepareRequest(b);for(let c of(f.push(JSON.stringify({custom_id:b.id,method:"POST",url:a.endpoint,body:a.body}),"\n"),a.warnings))g.push({requestId:b.id,warning:c})}let i=new Blob(f,{type:"application/jsonl"});f.length=0;let k=new FormData;(null==h?void 0:h.inputFileExpiresAfter)!=null&&k.append("expires_after",String(h.inputFileExpiresAfter)),k.append("file",i,"batch.jsonl");let l=(0,c.combineHeaders)(null==(e=(d=this.options.config).headers)?void 0:e.call(d),a.headers),{value:m}=await (0,c.postFormDataToApi)({url:this.getUrl("/files"),headers:l,formData:k,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(o),abortSignal:a.abortSignal,fetch:this.options.config.fetch}),{value:n}=await (0,c.postJsonToApi)({url:this.getUrl("/batches"),headers:l,body:{name:"ai-sdk-text-batch",input_file_id:m.id},failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(ad),abortSignal:a.abortSignal,fetch:this.options.config.fetch});return{batchId:n.batch_id,...ak(n),providerMetadata:{xai:{inputFileId:m.id,...null!=m.expires_at?{inputFileExpiresAt:new Date(1e3*m.expires_at).toISOString()}:{}}},warnings:g}}async doGetBatchStatus(a){return ak(await this.retrieveBatch(a))}async doCancelBatch(a){var b,d;return await (0,c.postJsonToApi)({url:this.getUrl(`/batches/${encodeURIComponent(a.batchId)}:cancel`),headers:(0,c.combineHeaders)(null==(d=(b=this.options.config).headers)?void 0:d.call(b),a.headers),body:{},failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(ad),abortSignal:a.abortSignal,fetch:this.options.config.fetch}),{}}async doListBatches(a){var b,d;let e=new URL(this.getUrl("/batches"));null!=a.limit&&e.searchParams.set("limit",String(a.limit)),null!=a.cursor&&e.searchParams.set("pagination_token",a.cursor);let{value:f}=await (0,c.getFromApi)({url:e.toString(),headers:(0,c.combineHeaders)(null==(d=(b=this.options.config).headers)?void 0:d.call(b),a.headers),failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(ai),abortSignal:a.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return{batches:f.batches.map(a=>({batchId:a.batch_id,...ak(a)})),...null!=f.pagination_token?{nextCursor:f.pagination_token}:{}}}async doGetBatchResults(a){if("pending"===ak(await this.retrieveBatch(a)).status)throw new b.InvalidArgumentError({argument:"batchId",message:`xAI batch "${a.batchId}" is not complete.`});return(0,c.convertAsyncIteratorToReadableStream)(this.iterateBatchResults(a))}async retrieveBatch(a){var b,d;let{value:e}=await (0,c.getFromApi)({url:this.getUrl(`/batches/${encodeURIComponent(a.batchId)}`),headers:(0,c.combineHeaders)(null==(d=(b=this.options.config).headers)?void 0:d.call(b),a.headers),failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(ad),abortSignal:a.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return e}async *iterateBatchResults(a){var b,d,e;let f;do{let g=new URLSearchParams({limit:String(1e3)});null!=f&&g.set("pagination_token",f);let{value:h}=await (0,c.getFromApi)({url:this.getUrl(`/batches/${encodeURIComponent(a.batchId)}/results?${g}`),headers:(0,c.combineHeaders)(null==(d=(b=this.options.config).headers)?void 0:d.call(b),a.headers),failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(ah),abortSignal:a.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});for(let b of h.results)yield await this.convertBatchResult(b,a.abortSignal);f=null!=(e=h.pagination_token)?e:void 0}while(null!=f)}async convertBatchResult(a,b){var d,e,f,g,h,i,j,k,l;let m=null==(d=a.batch_result)?void 0:d.error;if((null!=(f=null==(e=a.error_message)?void 0:e.length)?f:0)>0||(null==m?void 0:m.code)!=null&&0!==m.code&&"0"!==m.code||(null==m?void 0:m.code)==null&&(null!=(h=null==(g=null==m?void 0:m.message)?void 0:g.length)?h:0)>0){let b,c,d=(b=null==(k=(j=a).batch_result)?void 0:k.error,{message:j.error_message||(null==b?void 0:b.message)||"xAI batch request failed.",...(null==b?void 0:b.code)!=null&&0!==b.code&&"0"!==b.code?{code:String(b.code)}:{}});return{type:"text",id:a.batch_request_id,status:(c=String(l=null==m?void 0:m.code).toLowerCase(),1===l||"1"===c||"cancelled"===c||"batch_cancelled"===c)?"cancelled":"failed",error:d}}let o=null==(i=a.batch_result)?void 0:i.response;if((null==o?void 0:o.chat_get_completion)!=null){let b=await (0,c.safeValidateTypes)({value:o.chat_get_completion,schema:(0,c.zodSchema)(ag)});if(!b.success)return al(a.batch_request_id);let d=function(a){var b,d,e,f,g,h,i,j,k,l,m;let o,p,q,r;if(null!=a.error)return{success:!1,error:{message:a.error,...null!=a.code?{code:a.code}:{}}};let s=a.choices;if(null==s||0===s.length)return{success:!1,error:{message:"xAI returned a batch response without any choices.",code:"invalid_response"}};let t=[],u=new Set(s.filter(a=>"tool"===a.message.role).flatMap(a=>{var b;return(null!=(b=a.message.tool_calls)?b:[]).map(a=>a.id)}));for(let a of s){if("tool"===a.message.role){if(null!=a.message.content)for(let c of null!=(b=a.message.tool_calls)?b:[])t.push({type:"tool-result",toolCallId:c.id,toolName:c.function.name,result:a.message.content,dynamic:!0});continue}for(let b of(o=a,a.message.content&&t.push({type:"text",text:a.message.content}),a.message.reasoning_content&&t.push({type:"reasoning",text:a.message.reasoning_content}),null!=(d=a.message.tool_calls)?d:[]))t.push({type:"tool-call",toolCallId:b.id,toolName:b.function.name,input:b.function.arguments,...u.has(b.id)?{providerExecuted:!0,dynamic:!0}:{}})}for(let b of null!=(e=a.citations)?e:[])t.push({type:"source",sourceType:"url",id:b,url:b});return{success:!0,result:{content:t,finishReason:{unified:function(a){switch(a){case"stop":return"stop";case"length":return"length";case"tool_calls":case"function_call":return"tool-calls";case"content_filter":return"content-filter";default:return"other"}}(null==o?void 0:o.finish_reason),raw:null!=(f=null==o?void 0:o.finish_reason)?f:void 0},usage:a.usage?(p=null!=(k=null==(j=(i=a.usage).prompt_tokens_details)?void 0:j.cached_tokens)?k:0,q=null!=(m=null==(l=i.completion_tokens_details)?void 0:l.reasoning_tokens)?m:0,{inputTokens:{total:(r=p<=i.prompt_tokens)?i.prompt_tokens:i.prompt_tokens+p,noCache:r?i.prompt_tokens-p:i.prompt_tokens,cacheRead:p,cacheWrite:void 0},outputTokens:{total:i.completion_tokens+q,text:i.completion_tokens,reasoning:q},raw:i}):(0,c.createNullLanguageModelUsage)(),response:n(a),warnings:[],...((null==(g=a.usage)?void 0:g.cost_in_usd_ticks)!=null||null!=a.service_tier)&&{providerMetadata:{xai:{...(null==(h=a.usage)?void 0:h.cost_in_usd_ticks)!=null?{costInUsdTicks:a.usage.cost_in_usd_ticks}:{},...null!=a.service_tier?{serviceTier:a.service_tier}:{}}}}}}}(b.value);return d.success?{type:"text",id:a.batch_request_id,status:"succeeded",result:d.result}:{type:"text",id:a.batch_request_id,status:"failed",error:d.error}}if((null==o?void 0:o.image_generation)!=null){let d=await (0,c.safeValidateTypes)({value:o.image_generation,schema:(0,c.zodSchema)(ab)});if(!d.success)return{type:"image",id:a.batch_request_id,status:"failed",error:{message:"xAI returned an invalid image batch result.",code:"invalid_response"}};if(d.value.data.some(a=>!1===a.respect_moderation))return{type:"image",id:a.batch_request_id,status:"failed",error:{message:"Image generation was blocked due to a content policy violation."}};let e=await this.convertImageBatchResponse(d.value,b);return{type:"image",id:a.batch_request_id,status:"succeeded",result:e}}return al(a.batch_request_id)}async prepareRequest(a){if("text"===a.type){let{args:b,warnings:c}=await $.prepareRequest({modelId:a.modelId,options:a.options});return{endpoint:"/v1/responses",body:b,warnings:c}}let{prompt:b,n:d,size:e,aspectRatio:f,seed:g,files:h,mask:i,providerOptions:j}=a.options,l=[];null!=e&&l.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),null!=g&&l.push({type:"unsupported",feature:"seed"}),null!=i&&l.push({type:"unsupported",feature:"mask"});let m=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:j,schema:k}),n=(null!=h?h:[]).map(c.convertImageModelFileToDataUri),o={model:a.modelId,prompt:b,n:d,response_format:"b64_json"};return null!=f&&(o.aspect_ratio=f),(null==m?void 0:m.output_format)!=null&&(o.output_format=m.output_format),(null==m?void 0:m.sync_mode)!=null&&(o.sync_mode=m.sync_mode),(null==m?void 0:m.aspect_ratio)!=null&&null==f&&(o.aspect_ratio=m.aspect_ratio),(null==m?void 0:m.resolution)!=null&&(o.resolution=m.resolution),(null==m?void 0:m.quality)!=null&&(o.quality=m.quality),(null==m?void 0:m.user)!=null&&(o.user=m.user),1===n.length?o.image={url:n[0],type:"image_url"}:n.length>1&&(o.images=n.map(a=>({url:a,type:"image_url"}))),{endpoint:(null==h?void 0:h.length)?"/v1/images/edits":"/v1/images/generations",body:o,warnings:l}}async convertImageBatchResponse(a,d){var e;return{images:a.data.every(a=>null!=a.b64_json)?a.data.map(a=>a.b64_json):await Promise.all(a.data.map(async a=>{if(null!=a.b64_json)return(0,c.convertBase64ToUint8Array)(a.b64_json);if(null==a.url)throw new b.InvalidArgumentError({argument:"batchResult",message:"xAI returned an image without data or a URL."});let{value:e}=await (0,c.getFromApi)({url:a.url,validateUrl:!0,trustedOrigin:this.options.config.baseURL,abortSignal:d,failedResponseHandler:j,successfulResponseHandler:(0,c.createBinaryResponseHandler)(),fetch:this.options.config.fetch});return e})),warnings:[],response:{timestamp:new Date,modelId:"",headers:void 0},providerMetadata:{xai:{images:a.data.map(a=>null!=a.revised_prompt?{revisedPrompt:a.revised_prompt}:{}),...(null==(e=a.usage)?void 0:e.cost_in_usd_ticks)!=null?{costInUsdTicks:a.usage.cost_in_usd_ticks}:{}}}}}getUrl(a){var b;return`${null!=(b=this.options.config.baseURL)?b:"https://api.x.ai/v1"}${a}`}};function ak(a){var b,d,e,f,g,h;let i=(0,c.normalizeBatchRequestCounts)({total:null==(b=a.state)?void 0:b.num_requests,pending:null==(d=a.state)?void 0:d.num_pending,completed:null==(e=a.state)?void 0:e.num_success,failed:(null==(f=a.state)?void 0:f.num_error)!=null&&(null==(g=a.state)?void 0:g.num_cancelled)!=null?a.state.num_error+a.state.num_cancelled:void 0}),j=null!=a.cancel_time||null!=a.cancel_by_xai_message,k=function(a){if(null==a)return!1;let b=Date.parse(a);return!Number.isNaN(b)&&b<=Date.now()}(a.expire_time);return{status:j||k?"failed":null!=i&&i.total>0&&0===i.pending?"completed":"pending",...null!=i?{requestCounts:i}:{},...j?{error:{message:null!=(h=a.cancel_by_xai_message)?h:`xAI batch "${a.batch_id}" was cancelled.`,code:"batch_cancelled"}}:k?{error:{message:`xAI batch "${a.batch_id}" expired.`,code:"batch_expired"}}:{},...null!=a.create_time?{createdAt:a.create_time}:{},...null!=a.expire_time?{expiresAt:a.expire_time}:{}}}function al(a){return{type:"text",id:a,status:"failed",error:{message:"xAI returned an invalid Responses batch result.",code:"invalid_response"}}}function am(a){var b;let c={};null!=a.instructions&&(c.instructions=a.instructions),null!=a.voice&&(c.voice=a.voice);let d={};if(null!=a.inputAudioFormat&&(d.input={format:{type:a.inputAudioFormat.type,...null!=a.inputAudioFormat.rate?{rate:a.inputAudioFormat.rate}:{}}}),null!=a.outputAudioFormat&&(d.output={format:{type:a.outputAudioFormat.type,...null!=a.outputAudioFormat.rate?{rate:a.outputAudioFormat.rate}:{}}}),Object.keys(d).length>0&&(c.audio=d),null!=a.turnDetection)if("disabled"===a.turnDetection.type)c.turn_detection=null;else{let b={type:"server_vad"};null!=a.turnDetection.threshold&&(b.threshold=a.turnDetection.threshold),null!=a.turnDetection.silenceDurationMs&&(b.silence_duration_ms=a.turnDetection.silenceDurationMs),null!=a.turnDetection.prefixPaddingMs&&(b.prefix_padding_ms=a.turnDetection.prefixPaddingMs),c.turn_detection=b}if(null!=a.tools&&a.tools.length>0&&(c.tools=a.tools.map(a=>({type:a.type,name:a.name,description:a.description,parameters:a.parameters}))),null!=a.providerOptions){let d=a.providerOptions;if(Array.isArray(d.tools)){let a=null!=(b=c.tools)?b:[];c.tools=[...a,...d.tools]}for(let[a,b]of Object.entries(d))"tools"!==a&&(c[a]=b)}return c}var an=class{constructor(a,b){this.specificationVersion="v4",this.modelId=a,this.provider=b.provider,this.config=b}async doCreateClientSecret(a){var b;let c=null!=(b=this.config.fetch)?b:fetch,d=`${this.config.baseURL}/realtime/client_secrets`,e={};null!=a.expiresAfterSeconds&&(e.expires_after={seconds:a.expiresAfterSeconds});let f=await c(d,{method:"POST",headers:{...this.config.headers(),"Content-Type":"application/json"},body:JSON.stringify(e)});if(!f.ok){let a=await f.text();throw Error(`xAI realtime client secret request failed: ${f.status} ${a}`)}let g=await f.json();return{token:g.value,url:`wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`,expiresAt:g.expires_at}}getWebSocketConfig(a){return{url:a.url,protocols:[`xai-client-secret.${a.token}`]}}parseServerEvent(a){return function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;let u=a.type;switch(u){case"session.created":return{type:"session-created",sessionId:null==(b=a.session)?void 0:b.id,raw:a};case"session.updated":return{type:"session-updated",raw:a};case"conversation.created":case"mcp_list_tools.in_progress":case"mcp_list_tools.completed":case"mcp_list_tools.failed":case"response.mcp_call_arguments.delta":case"response.mcp_call_arguments.done":case"response.mcp_call.in_progress":case"response.mcp_call.completed":case"response.mcp_call.failed":default:return{type:"custom",rawType:u,raw:a};case"input_audio_buffer.speech_started":return{type:"speech-started",itemId:a.item_id,raw:a};case"input_audio_buffer.speech_stopped":return{type:"speech-stopped",itemId:a.item_id,raw:a};case"input_audio_buffer.committed":return{type:"audio-committed",itemId:a.item_id,previousItemId:a.previous_item_id,raw:a};case"conversation.item.added":return{type:"conversation-item-added",itemId:null!=(d=null==(c=a.item)?void 0:c.id)?d:a.item_id,item:a.item,raw:a};case"conversation.item.input_audio_transcription.completed":return{type:"input-transcription-completed",itemId:a.item_id,transcript:null!=(e=a.transcript)?e:"",raw:a};case"response.created":return{type:"response-created",responseId:null!=(g=null==(f=a.response)?void 0:f.id)?g:a.response_id,raw:a};case"response.done":return{type:"response-done",responseId:null!=(i=null==(h=a.response)?void 0:h.id)?i:a.response_id,status:null!=(k=null==(j=a.response)?void 0:j.status)?k:"completed",raw:a};case"response.output_item.added":return{type:"output-item-added",responseId:a.response_id,itemId:null!=(m=null==(l=a.item)?void 0:l.id)?m:a.item_id,raw:a};case"response.output_item.done":return{type:"output-item-done",responseId:a.response_id,itemId:null!=(o=null==(n=a.item)?void 0:n.id)?o:a.item_id,raw:a};case"response.content_part.added":return{type:"content-part-added",responseId:a.response_id,itemId:a.item_id,raw:a};case"response.content_part.done":return{type:"content-part-done",responseId:a.response_id,itemId:a.item_id,raw:a};case"response.output_audio.delta":return{type:"audio-delta",responseId:a.response_id,itemId:a.item_id,delta:a.delta,raw:a};case"response.output_audio.done":return{type:"audio-done",responseId:a.response_id,itemId:a.item_id,raw:a};case"response.output_audio_transcript.delta":return{type:"audio-transcript-delta",responseId:a.response_id,itemId:a.item_id,delta:a.delta,raw:a};case"response.output_audio_transcript.done":return{type:"audio-transcript-done",responseId:a.response_id,itemId:a.item_id,transcript:a.transcript,raw:a};case"response.text.delta":return{type:"text-delta",responseId:a.response_id,itemId:a.item_id,delta:a.delta,raw:a};case"response.text.done":return{type:"text-done",responseId:a.response_id,itemId:a.item_id,text:a.text,raw:a};case"response.function_call_arguments.delta":return{type:"function-call-arguments-delta",responseId:a.response_id,itemId:a.item_id,callId:a.call_id,delta:a.delta,raw:a};case"response.function_call_arguments.done":return{type:"function-call-arguments-done",responseId:a.response_id,itemId:a.item_id,callId:a.call_id,name:a.name,arguments:a.arguments,raw:a};case"error":return{type:"error",message:null!=(r=null!=(q=null==(p=a.error)?void 0:p.message)?q:a.message)?r:"Unknown error",code:null!=(t=null==(s=a.error)?void 0:s.code)?t:a.code,raw:a}}}(a)}serializeClientEvent(a){switch(a.type){case"session-update":return{type:"session.update",session:am(a.config)};case"input-audio-append":return{type:"input_audio_buffer.append",audio:a.audio};case"input-audio-commit":return{type:"input_audio_buffer.commit"};case"input-audio-clear":return{type:"input_audio_buffer.clear"};case"conversation-item-create":{let b=a.item;switch(b.type){case"text-message":return{type:"conversation.item.create",item:{type:"message",role:b.role,content:[{type:"input_text",text:b.text}]}};case"audio-message":return{type:"conversation.item.create",item:{type:"message",role:b.role,content:[{type:"input_audio",audio:b.audio}]}};case"function-call-output":return{type:"conversation.item.create",item:{type:"function_call_output",call_id:b.callId,output:b.output}}}break}case"conversation-item-truncate":break;case"response-create":return{type:"response.create",...null!=a.options?{response:{...null!=a.options.modalities?{modalities:a.options.modalities}:{},...null!=a.options.instructions?{instructions:a.options.instructions}:{}}}:{}};case"response-cancel":return{type:"response.cancel"}}}buildSessionConfig(a){return am(a)}},ao=e.z.object({output:e.z.string().describe("the output of the code execution"),error:e.z.string().optional().describe("any error that occurred")}),ap=(0,c.createProviderExecutedToolFactory)({id:"xai.code_execution",inputSchema:e.z.object({}).describe("no input parameters"),outputSchema:ao}),aq=e.z.object({description:e.z.string().describe("description of the image"),objects:e.z.array(e.z.string()).optional().describe("objects detected in the image")}),ar=(0,c.createProviderExecutedToolFactory)({id:"xai.view_image",inputSchema:e.z.object({}).describe("no input parameters"),outputSchema:aq}),as=e.z.object({transcript:e.z.string().optional().describe("transcript of the video"),description:e.z.string().describe("description of the video content"),duration:e.z.number().optional().describe("duration in seconds")}),at=(0,c.createProviderExecutedToolFactory)({id:"xai.view_x_video",inputSchema:e.z.object({}).describe("no input parameters"),outputSchema:as}),au={codeExecution:(a={})=>ap(a),fileSearch:a=>J(a),imageGeneration:(a={})=>N(a),mcpServer:a=>Q(a),viewImage:(a={})=>ar(a),viewXVideo:(a={})=>at(a),webSearch:(a={})=>T(a),xSearch:(a={})=>W(a)},av=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.looseObject({teamId:e.z.string().optional(),filePath:e.z.string().optional(),expiresAfter:e.z.number().int().min(3600).max(2592e3).optional()})));function aw(a){let b=encodeURIComponent(a);return"."===b?"%252E":".."===b?"%252E%252E":b}var ax=class{constructor(a){this.config=a,this.specificationVersion="v4"}get provider(){return this.config.provider}getFileId(a){let c=a.xai;if(null==c||""===c.trim())throw new b.InvalidArgumentError({argument:"file",message:"file reference is missing an 'xai' file id."});return c}getHeaders(a){return(0,c.combineHeaders)(this.config.headers(),a)}async uploadFile({data:a,mediaType:b,filename:d,abortSignal:e,headers:f,providerOptions:g}){var h,i;let k,l;try{k=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:g,schema:av})}catch(b){throw"stream"===a.type&&await a.stream.cancel(b).catch(()=>{}),b}let m=this.getHeaders(f),n=`${this.config.baseURL}/files`;if("stream"===a.type){let f=[];(null==k?void 0:k.expiresAfter)!=null&&f.push({type:"field",name:"expires_after",value:String(k.expiresAfter)}),(null==k?void 0:k.teamId)!=null&&f.push({type:"field",name:"team_id",value:k.teamId}),f.push({type:"file",name:"file",filename:d,mediaType:b,content:a.stream}),{value:l}=await (0,c.postMultipartStreamToApi)({url:n,headers:m,parts:f,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(o),abortSignal:e,fetch:this.config.fetch})}else{let f=new Blob([(0,c.convertInlineFileDataToUint8Array)(a)],{type:b}),g=new FormData;(null==k?void 0:k.expiresAfter)!=null&&g.append("expires_after",String(k.expiresAfter)),(null==k?void 0:k.teamId)!=null&&g.append("team_id",k.teamId),null!=d?g.append("file",f,d):g.append("file",f),{value:l}=await (0,c.postFormDataToApi)({url:n,headers:m,formData:g,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(o),abortSignal:e,fetch:this.config.fetch})}return{warnings:[],providerReference:{xai:l.id},...(null!=(h=l.filename)?h:d)?{filename:null!=(i=l.filename)?i:d}:{},...null!=b?{mediaType:b}:{},...null!=l.bytes?{byteSize:l.bytes}:{},...null!=l.created_at?{createdAt:new Date(1e3*l.created_at)}:{},...null!=l.expires_at?{expiresAt:new Date(1e3*l.expires_at)}:{},providerMetadata:{xai:this.toFileMetadata(l)}}}async getFileMetadata({file:a,abortSignal:b,headers:d}){let e=this.getFileId(a),{value:f}=await (0,c.getFromApi)({url:`${this.config.baseURL}/files/${aw(e)}`,headers:this.getHeaders(d),failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(o),abortSignal:b,fetch:this.config.fetch,validateUrl:!1});return{warnings:[],providerReference:{xai:f.id},...null!=f.filename?{filename:f.filename}:{},...null!=f.bytes?{byteSize:f.bytes}:{},...null!=f.created_at?{createdAt:new Date(1e3*f.created_at)}:{},...null!=f.expires_at?{expiresAt:new Date(1e3*f.expires_at)}:{},providerMetadata:{xai:this.toFileMetadata(f)}}}async downloadFile({file:a,abortSignal:b,headers:d}){var e;let f=this.getFileId(a),{value:g,responseHeaders:h}=await (0,c.getFromApi)({url:`${this.config.baseURL}/files/${aw(f)}/content`,headers:this.getHeaders(d),failedResponseHandler:j,successfulResponseHandler:(0,c.createBinaryStreamResponseHandler)(),abortSignal:b,fetch:this.config.fetch,validateUrl:!1}),i=null==(e=null==h?void 0:h["content-type"])?void 0:e.split(";")[0].trim();return{warnings:[],content:g,...i?{mediaType:i}:{}}}async deleteFile({file:a,abortSignal:b,headers:d}){let e=this.getFileId(a),{value:f}=await (0,c.deleteFromApi)({url:`${this.config.baseURL}/files/${aw(e)}`,headers:this.getHeaders(d),failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(p),abortSignal:b,fetch:this.config.fetch});return{warnings:[],providerReference:{xai:f.id},deleted:f.deleted}}toFileMetadata(a){return{...null!=a.filename?{filename:a.filename}:{},...null!=a.purpose?{purpose:a.purpose}:{},...null!=a.bytes?{bytes:a.bytes}:{},...null!=a.created_at?{createdAt:a.created_at}:{},...null!=a.status?{status:a.status}:{},...null!=a.expires_at?{expiresAt:a.expires_at}:{}}}},ay=e.z.string().min(1),az=e.z.enum(["480p","720p","1080p"]),aA=e.z.enum(["edit-video","extend-video","reference-to-video"]),aB={pollIntervalMs:e.z.number().positive().nullish(),pollTimeoutMs:e.z.number().positive().nullish(),resolution:az.nullish()},aC=e.z.looseObject({mode:aA.optional(),videoUrl:ay.optional(),referenceImageUrls:e.z.array(ay).min(1).max(7).optional(),referenceVoiceIds:e.z.array(ay).max(3).optional(),user:e.z.string().optional(),...aB}),aD=(0,c.lazySchema)(()=>(0,c.zodSchema)(aC)),aE={"1920x1080":"1080p","1280x720":"720p","854x480":"480p","640x480":"480p"};function aF(a){var b,c;return null==(c=null==(b=a.frameImages)?void 0:b.find(a=>"first_frame"===a.frameType))?void 0:c.image}var aG=a=>null!=a.mediaType&&"video"===(0,c.getTopLevelMediaType)(a.mediaType),aH=a=>null==a.mediaType||"image"===(0,c.getTopLevelMediaType)(a.mediaType);function aI(a){if("url"===a.type)return a.url;let b="string"==typeof a.data?a.data:(0,c.convertUint8ArrayToBase64)(a.data);return`data:${a.mediaType};base64,${b}`}function aJ(a){var b,c;return null!=(c=null==(b=a.inputReferences)?void 0:b.some(aH))&&c}var aK=class{constructor(a,b){this.modelId=a,this.config=b,this.specificationVersion="v4",this.maxVideosPerCall=1}get provider(){return this.config.provider}async buildRequestBody(a){var b,d,e;let f=[],g=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:a.providerOptions,schema:aD}),h=function(a,b){if((null==b?void 0:b.mode)!=null)return b.mode;if((null==b?void 0:b.videoUrl)!=null)return"edit-video";let c=null!=a.frameImages&&a.frameImages.length>0,d=(null==b?void 0:b.referenceImageUrls)!=null&&b.referenceImageUrls.length>0;if(!c&&(aJ(a)||d))return"reference-to-video"}(a,g),i="edit-video"===h,j="extend-video"===h,k="reference-to-video"===h;null!=a.fps&&f.push({type:"unsupported",feature:"fps",details:"xAI video models do not support custom FPS."}),null!=a.seed&&f.push({type:"unsupported",feature:"seed",details:"xAI video models do not support seed."}),null!=a.n&&a.n>1&&f.push({type:"unsupported",feature:"n",details:"xAI video models do not support generating multiple videos per call. Only 1 video will be generated."}),i&&null!=a.duration&&f.push({type:"unsupported",feature:"duration",details:"xAI video editing does not support custom duration."}),i&&null!=a.aspectRatio&&f.push({type:"unsupported",feature:"aspectRatio",details:"xAI video editing does not support custom aspect ratio."}),i&&((null==g?void 0:g.resolution)!=null||null!=a.resolution)&&f.push({type:"unsupported",feature:"resolution",details:"xAI video editing does not support custom resolution."}),j&&null!=a.aspectRatio&&f.push({type:"unsupported",feature:"aspectRatio",details:"xAI video extension does not support custom aspect ratio."}),j&&((null==g?void 0:g.resolution)!=null||null!=a.resolution)&&f.push({type:"unsupported",feature:"resolution",details:"xAI video extension does not support custom resolution."});let l={model:this.modelId,prompt:a.prompt},m=!i&&!j;if(i||null==a.duration||(l.duration=a.duration),i||j||null==a.aspectRatio||(l.aspect_ratio=a.aspectRatio),m&&(null==g?void 0:g.resolution)!=null)l.resolution=g.resolution;else if(m&&null!=a.resolution){let b=aE[a.resolution];null!=b?l.resolution=b:f.push({type:"unsupported",feature:"resolution",details:`Unrecognized resolution "${a.resolution}". Use providerOptions.xai.resolution with "480p", "720p", or "1080p" instead.`})}i&&(l.video={url:g.videoUrl}),j&&(l.video={url:g.videoUrl});let n=null!=(b=aF(a))?b:a.image;if(null!=n)if(aG(n)){let b=null!=aF(a);f.push({type:"unsupported",feature:b?"frameImages":"image",details:'xAI does not accept a video as a start/frame image. The video was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video instead.'})}else l.image={url:aI(n)};let o=null==(e=null==(d=a.frameImages)?void 0:d.find(a=>"last_frame"===a.frameType))?void 0:e.image;if(null!=o&&f.push({type:"unsupported",feature:"frameImages",details:aG(o)?'xAI does not accept a video as a start/frame image. The video last frame was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video instead.':'xAI video models do not support last_frame. Use providerOptions.xai.mode "extend-video" to continue from a video\'s last frame. The last frame image was ignored.'}),k){let b=function(a,b,c){if(null!=a.inputReferences&&a.inputReferences.length>0){let b=[];for(let d of a.inputReferences){if(!aH(d)){c.push({type:"unsupported",feature:"inputReferences",details:aG(d)?'xAI reference-to-video accepts image references only. The video reference was ignored. Use providerOptions.xai.mode "extend-video" to continue from a video.':"xAI reference-to-video accepts image references only. The non-image reference was ignored."});continue}b.push(d)}return b.length>0?b.map(a=>({url:aI(a)})):void 0}if((null==b?void 0:b.referenceImageUrls)!=null&&b.referenceImageUrls.length>0)return b.referenceImageUrls.map(a=>({url:a}))}(a,g,f);null!=b?l.reference_images=b:f.push({type:"unsupported",feature:"referenceImages",details:"xAI reference-to-video requires at least one image reference. The video will be generated without reference images."});let c=null==g?void 0:g.referenceVoiceIds;null!=c&&c.length>0&&(l.reference_audios=c.map(a=>({voice_id:a}))),"1080p"===l.resolution&&(f.push({type:"unsupported",feature:"resolution",details:"xAI reference-to-video is limited to 720p. The request was downgraded from 1080p to 720p."}),l.resolution="720p")}if("1080p"===l.resolution&&"grok-imagine-video"===this.modelId&&f.push({type:"unsupported",feature:"resolution",details:'xAI model "grok-imagine-video" does not support 1080p. Use "grok-imagine-video-1.5" for 1080p, or a lower resolution. The request was sent with 1080p.'}),null!=a.inputReferences&&a.inputReferences.length>0&&!k&&f.push({type:"unsupported",feature:"inputReferences",details:aJ(a)?"xAI only supports inputReferences for reference-to-video generation. The reference images were ignored.":"xAI reference-to-video requires at least one image reference. The references were ignored."}),(null==g?void 0:g.referenceVoiceIds)!=null&&g.referenceVoiceIds.length>0&&!k&&f.push({type:"unsupported",feature:"referenceVoiceIds",details:"xAI only supports reference voices for reference-to-video generation. The reference voices were ignored."}),j||(null==g?void 0:g.user)===void 0||(l.user=g.user),null!=g)for(let[a,b]of Object.entries(g))["mode","pollIntervalMs","pollTimeoutMs","resolution","videoUrl","referenceImageUrls","referenceVoiceIds","user"].includes(a)||(l[a]=b);return{body:l,warnings:f,xaiOptions:g,isEdit:i,isExtension:j,hasReferenceImages:k,effectiveMode:h}}async doStart(a){var d,e,f,g;let h,i=null!=(f=null==(e=null==(d=this.config._internal)?void 0:d.currentDate)?void 0:e.call(d))?f:new Date,{body:k,warnings:l,isEdit:m,isExtension:n}=await this.buildRequestBody(a),o=null!=(g=this.config.baseURL)?g:"https://api.x.ai/v1";h=m?`${o}/videos/edits`:n?`${o}/videos/extensions`:`${o}/videos/generations`;let{value:p,responseHeaders:q}=await (0,c.postJsonToApi)({url:h,headers:(0,c.combineHeaders)(this.config.headers(),a.headers),body:k,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(aL),abortSignal:a.abortSignal,fetch:this.config.fetch}),r=p.request_id;if(!r)throw new b.AISDKError({name:"XAI_VIDEO_GENERATION_ERROR",message:"No request_id returned from xAI API."});return{operation:{requestId:r},warnings:l,response:{timestamp:i,modelId:this.modelId,headers:q}}}async doStatus(a){var b,d,e,f,g,h,i,k,l,m,n;let o,p=null!=(e=null==(d=null==(b=this.config._internal)?void 0:b.currentDate)?void 0:d.call(b))?e:new Date,{requestId:q}=a.operation,r=null!=(f=this.config.baseURL)?f:"https://api.x.ai/v1",{value:s,responseHeaders:t}=await (0,c.getFromApi)({url:`${r}/videos/${"."===(o=encodeURIComponent(q))?"%252E":".."===o?"%252E%252E":o}`,validateUrl:!1,headers:(0,c.combineHeaders)(this.config.headers(),a.headers),successfulResponseHandler:aQ,failedResponseHandler:j,abortSignal:a.abortSignal,fetch:this.config.fetch});if("expired"===s.status)return{status:"error",error:"Video generation request expired.",response:{timestamp:p,modelId:this.modelId,headers:t}};if("failed"===s.status){let a=null!=(i=null==(g=s.error)?void 0:g.message)?i:null==(h=s.error)?void 0:h.code;return{status:"error",error:null!=a?`Video generation failed: ${a}`:"Video generation failed.",response:{timestamp:p,modelId:this.modelId,headers:t}}}return"done"===s.status||null==s.status&&(null==(k=s.video)?void 0:k.url)?(null==(l=s.video)?void 0:l.respect_moderation)===!1?{status:"error",error:"Video generation was blocked due to a content policy violation.",response:{timestamp:p,modelId:this.modelId,headers:t}}:(null==(m=s.video)?void 0:m.url)?{status:"completed",videos:[{type:"url",url:s.video.url,mediaType:"video/mp4"}],warnings:[],response:{timestamp:p,modelId:this.modelId,headers:t},providerMetadata:{xai:{requestId:q,videoUrl:s.video.url,...null!=s.video.duration?{duration:s.video.duration}:{},...(null==(n=s.usage)?void 0:n.cost_in_usd_ticks)!=null?{costInUsdTicks:s.usage.cost_in_usd_ticks}:{},...null!=s.progress?{progress:s.progress}:{}}}}:{status:"error",error:"Video generation completed but no video URL was returned.",response:{timestamp:p,modelId:this.modelId,headers:t}}:{status:"pending",response:{timestamp:p,modelId:this.modelId,headers:t}}}},aL=e.z.object({request_id:e.z.string().nullish()}),aM=e.z.object({status:e.z.string().nullish(),video:e.z.object({url:e.z.string(),duration:e.z.number().nullish(),respect_moderation:e.z.boolean().nullish()}).nullish(),model:e.z.string().nullish(),usage:e.z.object({cost_in_usd_ticks:e.z.number().nullish()}).nullish(),progress:e.z.number().nullish(),error:e.z.object({code:e.z.string().nullish(),message:e.z.string().nullish()}).nullish()}),aN=(0,c.createJsonResponseHandler)(aM),aO=new TextDecoder;async function aP({response:a,url:d,requestBodyValues:e}){if(null==a.body)return"";let f=a.body.getReader(),g=[],h=0;try{for(;;){let{done:i,value:j}=await f.read();if(i)break;if((h+=j.length)>1048576)throw new b.APICallError({message:"xAI video status response exceeded 1048576 bytes",url:d,requestBodyValues:e,statusCode:a.status,responseHeaders:(0,c.extractResponseHeaders)(a)});g.push(j)}}finally{f.releaseLock()}let i=new Uint8Array(h),j=0;for(let a of g)i.set(a,j),j+=a.length;return aO.decode(i)}var aQ=async a=>{if(202===a.response.status){let b=(0,c.extractResponseHeaders)(a.response),d=await aP(a);if(0===d.trim().length)return{responseHeaders:b,value:{status:"pending"}};let e=await (0,c.safeParseJSON)({text:d,schema:aM});return{responseHeaders:b,value:e.success?e.value:{status:"pending"}}}return aN(a)},aR=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({sampleRate:e.z.union([e.z.literal(8e3),e.z.literal(16e3),e.z.literal(22050),e.z.literal(24e3),e.z.literal(44100),e.z.literal(48e3)]).nullish(),bitRate:e.z.union([e.z.literal(32e3),e.z.literal(64e3),e.z.literal(96e3),e.z.literal(128e3),e.z.literal(192e3)]).nullish(),optimizeStreamingLatency:e.z.union([e.z.literal(0),e.z.literal(1),e.z.literal(2)]).nullish(),textNormalization:e.z.boolean().nullish(),withTimestamps:e.z.boolean().nullish(),replace:e.z.record(e.z.string(),e.z.string()).nullish()}))),aS=class a{constructor(a,b){this.modelId=a,this.config=b,this.specificationVersion="v4"}static[d.WORKFLOW_SERIALIZE](a){return(0,c.serializeModelOptions)({modelId:a.modelId,config:a.config})}static[d.WORKFLOW_DESERIALIZE](b){return new a(b.modelId,b.config)}get provider(){return this.config.provider}async getArgs({text:a,voice:b="eve",outputFormat:d="mp3",instructions:e,speed:f,language:g="auto",providerOptions:h}){let i=[],j=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:h,schema:aR}),k="mp3";["mp3","wav","pcm","mulaw","alaw"].includes(d)?k=d:i.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${d}. Using mp3 instead.`}),null!=e&&i.push({type:"unsupported",feature:"instructions",details:"xAI speech models do not support the `instructions` option. Use xAI speech tags in `text` to control delivery."});let l={codec:k};return(null==j?void 0:j.sampleRate)!=null&&(l.sample_rate=j.sampleRate),(null==j?void 0:j.bitRate)!=null&&("mp3"===k?l.bit_rate=j.bitRate:i.push({type:"unsupported",feature:"providerOptions",details:"xAI `bitRate` is supported only for mp3 output. It was ignored."})),{requestBody:{text:a,voice_id:b,language:g,output_format:l,speed:f,optimize_streaming_latency:null==j?void 0:j.optimizeStreamingLatency,text_normalization:null==j?void 0:j.textNormalization,with_timestamps:null==j?void 0:j.withTimestamps,replace:null==j?void 0:j.replace},warnings:i,withTimestamps:(null==j?void 0:j.withTimestamps)===!0}}async doGenerate(a){var b,d,e;let f,g,h=null!=(e=null==(d=null==(b=this.config._internal)?void 0:b.currentDate)?void 0:d.call(b))?e:new Date,{requestBody:i,warnings:k,withTimestamps:l}=await this.getArgs(a),{value:m,responseHeaders:n,rawValue:o}=await (0,c.postJsonToApi)({url:`${this.config.baseURL}/tts`,headers:(0,c.combineHeaders)(this.config.headers?await (0,c.resolve)(this.config.headers):void 0,a.headers),body:i,failedResponseHandler:j,successfulResponseHandler:l?(0,c.createJsonResponseHandler)(aT):(0,c.createBinaryResponseHandler)(),abortSignal:a.abortSignal,fetch:this.config.fetch});f=m instanceof Uint8Array?m:null!=(g=m).audio?(0,c.convertBase64ToUint8Array)(g.audio):new Uint8Array(0);let p=null==n?void 0:n["x-trace-id"];return{audio:f,warnings:k,request:{body:JSON.stringify(i)},response:{timestamp:h,modelId:this.modelId,headers:n,body:o},providerMetadata:{xai:{...null!=p?{traceId:p}:{},...(null==g?void 0:g.duration)!=null?{duration:g.duration}:{},...(null==g?void 0:g.content_type)!=null?{contentType:g.content_type}:{},...(null==g?void 0:g.audio_timestamps)!=null?{audioTimestamps:{graphChars:g.audio_timestamps.graph_chars,graphTimes:g.audio_timestamps.graph_times}}:{}}}}}},aT=e.z.object({audio:e.z.string().nullish(),content_type:e.z.string().nullish(),duration:e.z.number().nullish(),audio_timestamps:e.z.object({graph_chars:e.z.array(e.z.string()),graph_times:e.z.array(e.z.tuple([e.z.number(),e.z.number()]))}).nullish()}),aU=(0,c.lazySchema)(()=>(0,c.zodSchema)(e.z.object({audioFormat:e.z.enum(["pcm","mulaw","alaw"]).nullish(),sampleRate:e.z.union([e.z.literal(8e3),e.z.literal(16e3),e.z.literal(22050),e.z.literal(24e3),e.z.literal(44100),e.z.literal(48e3)]).nullish(),language:e.z.string().nullish(),format:e.z.boolean().nullish(),multichannel:e.z.boolean().nullish(),channels:e.z.number().int().min(2).max(8).nullish(),diarize:e.z.boolean().nullish(),keyterm:e.z.union([e.z.string(),e.z.array(e.z.string())]).nullish(),fillerWords:e.z.boolean().nullish(),streaming:e.z.object({interimResults:e.z.boolean().optional(),endpointing:e.z.number().int().min(0).max(5e3).optional(),smartTurn:e.z.number().min(0).max(1).optional(),smartTurnTimeout:e.z.number().int().min(1).max(5e3).optional()}).optional()}))),aV=class a{constructor(a,b){this.modelId=a,this.config=b,this.specificationVersion="v4"}static[d.WORKFLOW_SERIALIZE](a){return(0,c.serializeModelOptions)({modelId:a.modelId,config:a.config})}static[d.WORKFLOW_DESERIALIZE](b){return new a(b.modelId,b.config)}get provider(){return this.config.provider}async getArgs({audio:a,mediaType:b,providerOptions:d}){let e=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:d,schema:aU}),f=new FormData;for(let[a,b]of Object.entries({audio_format:null==e?void 0:e.audioFormat,sample_rate:null==e?void 0:e.sampleRate,language:null==e?void 0:e.language,format:null==e?void 0:e.format,multichannel:null==e?void 0:e.multichannel,channels:null==e?void 0:e.channels,diarize:null==e?void 0:e.diarize,filler_words:null==e?void 0:e.fillerWords}))null!=b&&f.append(a,String(b));if((null==e?void 0:e.keyterm)!=null)for(let a of Array.isArray(e.keyterm)?e.keyterm:[e.keyterm])f.append("keyterm",a);let g=a instanceof Uint8Array?new Blob([a]):new Blob([(0,c.convertBase64ToUint8Array)(a)]),h=(0,c.mediaTypeToExtension)(b);return f.append("file",new File([g],"audio",{type:b}),`audio.${h}`),{formData:f,warnings:[]}}async doGenerate(a){var b,d,e,f,g,h,i,k,l;let m=null!=(e=null==(d=null==(b=this.config._internal)?void 0:b.currentDate)?void 0:d.call(b))?e:new Date,{formData:n,warnings:o}=await this.getArgs(a),{value:p,responseHeaders:q,rawValue:r}=await (0,c.postFormDataToApi)({url:`${null!=(f=this.config.baseURL)?f:"https://api.x.ai/v1"}/stt`,headers:(0,c.combineHeaders)(null==(h=(g=this.config).headers)?void 0:h.call(g),a.headers),formData:n,failedResponseHandler:j,successfulResponseHandler:(0,c.createJsonResponseHandler)(aX),abortSignal:a.abortSignal,fetch:this.config.fetch});return{text:p.text,segments:null!=(k=null==(i=p.words)?void 0:i.map(a=>({text:a.text,startSecond:a.start,endSecond:a.end})))?k:[],language:p.language||void 0,durationInSeconds:null!=(l=p.duration)?l:void 0,warnings:o,response:{timestamp:m,modelId:this.modelId,headers:q,body:r}}}async doStream(a){var d,e,f,g,h,i,j,k;let l=null!=(f=null==(e=null==(d=this.config._internal)?void 0:d.currentDate)?void 0:e.call(d))?f:new Date,m=[],n=await (0,c.parseProviderOptions)({provider:"xai",providerOptions:a.providerOptions,schema:aU});if((null==n?void 0:n.multichannel)===!0&&null==n.channels)throw new b.InvalidArgumentError({argument:"providerOptions",message:"providerOptions.xai.channels is required when providerOptions.xai.multichannel is true"});(null==n?void 0:n.format)!=null&&m.push({type:"unsupported",feature:"providerOptions.xai.format",details:"xAI streaming transcription does not support format."}),(null==n?void 0:n.audioFormat)==null&&"audio/pcm"!==(k=a.inputAudioFormat.type)&&"audio/pcmu"!==k&&"audio/pcma"!==k&&m.push({type:"other",message:`Unrecognized inputAudioFormat.type "${a.inputAudioFormat.type}"; falling back to raw PCM encoding. Use audio/pcm, audio/pcmu, or audio/pcma, or set providerOptions.xai.audioFormat explicitly.`});let o=function({baseURL:a,inputAudioFormat:b,providerOptions:d}){var e,f,g,h,i,j;let k=(0,c.toWebSocketUrl)(`${a}/stt`);if(aW(k,"sample_rate",null!=(e=null==d?void 0:d.sampleRate)?e:b.rate),aW(k,"encoding",null!=(f=null==d?void 0:d.audioFormat)?f:function(a){switch(a){case"audio/pcmu":return"mulaw";case"audio/pcma":return"alaw";default:return"pcm"}}(b.type)),aW(k,"language",null==d?void 0:d.language),aW(k,"diarize",null==d?void 0:d.diarize),aW(k,"filler_words",null==d?void 0:d.fillerWords),aW(k,"multichannel",null==d?void 0:d.multichannel),aW(k,"channels",null==d?void 0:d.channels),aW(k,"interim_results",null==(g=null==d?void 0:d.streaming)?void 0:g.interimResults),aW(k,"endpointing",null==(h=null==d?void 0:d.streaming)?void 0:h.endpointing),aW(k,"smart_turn",null==(i=null==d?void 0:d.streaming)?void 0:i.smartTurn),aW(k,"smart_turn_timeout",null==(j=null==d?void 0:d.streaming)?void 0:j.smartTurnTimeout),(null==d?void 0:d.keyterm)!=null)for(let a of Array.isArray(d.keyterm)?d.keyterm:[d.keyterm])k.searchParams.append("keyterm",a);return k}({baseURL:null!=(g=this.config.baseURL)?g:"https://api.x.ai/v1",inputAudioFormat:a.inputAudioFormat,providerOptions:n}),p=(0,c.combineHeaders)(null==(i=(h=this.config).headers)?void 0:i.call(h),a.headers);return{request:{body:o.toString()},response:{timestamp:l,modelId:this.modelId},stream:function({webSocket:a,url:b,headers:d,warnings:e,language:f,expectedDoneCount:g,audio:h,abortSignal:i,includeRawChunks:j}){let k=!1,l=()=>{};return new ReadableStream({start:m=>{let n,o,p,q=new Map,r=new Map,s=new Map;l=a=>{null!=o?o.cancel().catch(()=>{}):h.cancel().catch(()=>{}),null==p||p.close(a)};let t=a=>{k||(k=!0,l(),m.error(a))},u=async a=>{o=h.getReader();try{for(;;){let{done:b,value:d}=await o.read();if(b||k)break;a.send(d instanceof Uint8Array?d:(0,c.convertBase64ToUint8Array)(d)),await (0,c.waitForWebSocketBufferDrain)(a)}}finally{o.releaseLock(),o=void 0}k||a.send(JSON.stringify({type:"audio.done"}))};p=(0,c.connectToWebSocket)({url:b,headers:d,webSocket:a,abortSignal:i,onAbort:t,onProcessingError:t,onMessageText:async a=>{var b,d,h,i,o,v,w,x,y,z,A;let B=await (0,c.safeParseJSON)({text:a});if(!B.success)return;let C=B.value;switch(j&&m.enqueue({type:"raw",rawValue:C}),C.type){case"transcript.created":{m.enqueue({type:"stream-start",warnings:e});let a=null==p?void 0:p.socket;if(null==a){t(Error("WebSocket is not connected."));break}u(a).catch(t);break}case"transcript.partial":{let a=null==(z=C.channel_index)?void 0:`channel-${z}`,c=null!=(b=C.channel_index)?b:0;if(C.is_final&&C.speech_final){let b={...null!=(A=C).start?{startSecond:A.start}:{},...null!=A.start&&null!=A.duration?{endSecond:A.start+A.duration}:{}};C.text&&r.set(c,[...null!=(d=r.get(c))?d:[],C.text]),s.delete(c),m.enqueue({type:"transcript-final",id:a,text:null!=(h=C.text)?h:"",...b,channelIndex:C.channel_index})}else s.set(c,null!=(i=C.text)?i:""),m.enqueue({type:"transcript-partial",id:a,text:null!=(o=C.text)?o:"",startSecond:C.start,durationInSeconds:C.duration,channelIndex:C.channel_index});break}case"transcript.done":{let a=null!=(v=C.channel_index)?v:0,b=[...null!=(w=r.get(a))?w:[],...s.get(a)?[s.get(a)]:[]].join(" ");q.set(a,C.text||b),n=null!=(x=C.duration)?x:n,(()=>{if(k||q.size<g)return;k=!0;let a=[...q.entries()].sort(([a],[b])=>a-b).map(([,a])=>a).join("\n");m.enqueue({type:"finish",text:a,segments:[],language:f,durationInSeconds:n}),m.close(),l(1e3)})();break}case"error":t(Error(null!=(y=C.message)?y:"xAI STT error"))}},onSocketError:()=>{t(Error("xAI streaming transcription error."+(null==a?" Note: the native WebSocket implementation in browsers, Node.js, Deno, and Bun cannot send the Authorization header required by xAI. Pass a header-capable WebSocket implementation (e.g. the 'ws' package) via createXai({ webSocket }).":"")))},onClose:()=>{k||(k=!0,l(),m.close())}})},cancel:()=>{k||(k=!0,l())}})}({webSocket:this.config.webSocket,url:o,headers:p,warnings:m,language:null!=(j=null==n?void 0:n.language)?j:void 0,expectedDoneCount:(null==n?void 0:n.multichannel)===!0?n.channels:1,audio:a.audio,abortSignal:a.abortSignal,includeRawChunks:a.includeRawChunks})}}};function aW(a,b,c){null!=c&&a.searchParams.set(b,String(c))}var aX=e.z.object({text:e.z.string(),language:e.z.string().nullish(),duration:e.z.number().nullish(),words:e.z.array(e.z.object({text:e.z.string(),start:e.z.number(),end:e.z.number()})).nullish()});function aY(a={}){var d;let e=(0,c.withoutTrailingSlash)(null!=(d=a.baseURL)?d:"https://api.x.ai/v1"),f=()=>(0,c.withUserAgentSuffix)({Authorization:`Bearer ${(0,c.loadApiKey)({apiKey:a.apiKey,environmentVariableName:"XAI_API_KEY",description:"xAI API key"})}`,...a.headers},"ai-sdk/xai/5.0.7"),g=b=>new $(b,{provider:"xai.responses",baseURL:e,headers:f,generateId:c.generateId,fetch:a.fetch}),h=b=>new l(b,{provider:"xai.image",baseURL:e,headers:f,fetch:a.fetch}),i=b=>new aK(b,{provider:"xai.video",baseURL:e,headers:f,fetch:a.fetch}),j=b=>new an(b,{provider:"xai.realtime",baseURL:null!=e?e:"https://api.x.ai/v1",headers:f,fetch:a.fetch}),k=()=>new aS("",{provider:"xai.speech",baseURL:e,headers:f,fetch:a.fetch}),m=()=>new aV("",{provider:"xai.transcription",baseURL:e,headers:f,fetch:a.fetch,webSocket:a.webSocket}),n=Object.assign(a=>j(a),{getToken:async a=>{let b=j(a.model),c=await b.doCreateClientSecret({sessionConfig:a.sessionConfig,expiresAfterSeconds:a.expiresAfterSeconds});return{token:c.token,url:c.url,expiresAt:c.expiresAt}}}),o=a=>g(a);return o.specificationVersion="v4",o.languageModel=g,o.responses=g,o.embeddingModel=a=>{throw new b.NoSuchModelError({modelId:a,modelType:"embeddingModel"})},o.textEmbeddingModel=o.embeddingModel,o.imageModel=h,o.image=h,o.videoModel=i,o.video=i,o.experimental_realtime=n,o.speechModel=k,o.speech=k,o.transcriptionModel=m,o.transcription=m,o.files=()=>new ax({provider:"xai.files",baseURL:e,headers:f,fetch:a.fetch}),o.experimental_batch=()=>new aj({provider:"xai.batch",config:{provider:"xai.responses",baseURL:e,headers:f,generateId:c.generateId,fetch:a.fetch}}),o.tools=au,o}aY(),a.s(["createXai",0,aY])},272380,a=>{"use strict";var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E=a.i(634531),F=a.i(22372),G=a.i(53112),H=Object.defineProperty,I=Object.defineProperties,J=Object.getOwnPropertyDescriptors,K=Object.getOwnPropertySymbols,L=Object.prototype.hasOwnProperty,M=Object.prototype.propertyIsEnumerable,N=a=>{throw TypeError(a)},O=(a,b,c)=>b in a?H(a,b,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[b]=c,P=(a,b)=>{for(var c in b||(b={}))L.call(b,c)&&O(a,c,b[c]);if(K)for(var c of K(b))M.call(b,c)&&O(a,c,b[c]);return a},Q=(a,b)=>I(a,J(b)),R=(a,b)=>{var c={};for(var d in a)L.call(a,d)&&0>b.indexOf(d)&&(c[d]=a[d]);if(null!=a&&K)for(var d of K(a))0>b.indexOf(d)&&M.call(a,d)&&(c[d]=a[d]);return c},S=(a,b,c)=>(b.has(a)||N("Cannot read from private field"),c?c.call(a):b.get(a)),T="vercel.ai.error",U=Symbol.for(T),V=class a extends(d=Error,c=U,d){constructor({name:a,message:b,cause:d}){super(b),this[c]=!0,this.name=a,this.cause=d}static isInstance(b){return a.hasMarker(b,T)}static hasMarker(a,b){let c=Symbol.for(b);return null!=a&&"object"==typeof a&&c in a&&"boolean"==typeof a[c]&&!0===a[c]}},W="AI_APICallError",X=`vercel.ai.error.${W}`,Y=Symbol.for(X),Z=class extends(f=V,e=Y,f){constructor({message:a,url:b,requestBodyValues:c,statusCode:d,responseHeaders:f,responseBody:g,cause:h,isRetryable:i=null!=d&&(408===d||409===d||429===d||d>=500),data:j}){super({name:W,message:a,cause:h}),this[e]=!0,this.url=b,this.requestBodyValues=c,this.statusCode=d,this.responseHeaders=f,this.responseBody=g,this.isRetryable=i,this.data=j}static isInstance(a){return V.hasMarker(a,X)}},$="AI_EmptyResponseBodyError",_=`vercel.ai.error.${$}`,aa=Symbol.for(_),ab=class extends(h=V,g=aa,h){constructor({message:a="Empty response body"}={}){super({name:$,message:a}),this[g]=!0}static isInstance(a){return V.hasMarker(a,_)}},ac=Symbol.for("vercel.ai.error.AI_EvaluationUnsupportedQuestionTypeError");function ad(a){return null==a?"unknown error":"string"==typeof a?a:a instanceof Error?a.toString():JSON.stringify(a)}var ae="AI_InvalidArgumentError",af=`vercel.ai.error.${ae}`,ag=Symbol.for(af),ah=class extends(j=V,i=ag,j){constructor({message:a,cause:b,argument:c}){super({name:ae,message:a,cause:b}),this[i]=!0,this.argument=c}static isInstance(a){return V.hasMarker(a,af)}},ai="AI_InvalidPromptError",aj=`vercel.ai.error.${ai}`,ak=Symbol.for(aj),al=class extends(l=V,k=ak,l){constructor({prompt:a,message:b,cause:c}){super({name:ai,message:`Invalid prompt: ${b}`,cause:c}),this[k]=!0,this.prompt=a}static isInstance(a){return V.hasMarker(a,aj)}},am="AI_InvalidResponseDataError",an=`vercel.ai.error.${am}`,ao=Symbol.for(an),ap=class extends(n=V,m=ao,n){constructor({data:a,message:b=`Invalid response data: ${JSON.stringify(a)}.`}){super({name:am,message:b}),this[m]=!0,this.data=a}static isInstance(a){return V.hasMarker(a,an)}},aq="AI_JSONParseError",ar=`vercel.ai.error.${aq}`,as=Symbol.for(ar),at=class extends(p=V,o=as,p){constructor({text:a,cause:b}){super({name:aq,message:`JSON parsing failed: Text: ${a}.
|
|
213
|
+
Error message: ${ad(b)}`,cause:b}),this[o]=!0,this.text=a}static isInstance(a){return V.hasMarker(a,ar)}},au="AI_LoadAPIKeyError",av=`vercel.ai.error.${au}`,aw=Symbol.for(av),ax=class extends(r=V,q=aw,r){constructor({message:a}){super({name:au,message:a}),this[q]=!0}static isInstance(a){return V.hasMarker(a,av)}},ay="AI_LoadSettingError",az=`vercel.ai.error.${ay}`,aA=Symbol.for(az),aB=class extends(t=V,s=aA,t){constructor({message:a}){super({name:ay,message:a}),this[s]=!0}static isInstance(a){return V.hasMarker(a,az)}},aC="AI_NoContentGeneratedError",aD=`vercel.ai.error.${aC}`,aE=Symbol.for(aD),aF=class extends(v=V,u=aE,v){constructor({message:a="No content generated."}={}){super({name:aC,message:a}),this[u]=!0}static isInstance(a){return V.hasMarker(a,aD)}},aG=Symbol.for("vercel.ai.error.AI_NoSuchModelError");Symbol.for("vercel.ai.error.AI_NoSuchProviderReferenceError");Symbol.for("vercel.ai.error.AI_TooManyEmbeddingValuesForCallError");var aH="AI_TypeValidationError",aI=`vercel.ai.error.${aH}`,aJ=Symbol.for(aI),aK=class a extends(x=V,w=aJ,x){constructor({value:a,cause:b,context:c}){let d="Type validation failed";if((null==c?void 0:c.field)&&(d+=` for ${c.field}`),(null==c?void 0:c.entityName)||(null==c?void 0:c.entityId)){d+=" (";const a=[];c.entityName&&a.push(c.entityName),c.entityId&&a.push(`id: "${c.entityId}"`),d+=a.join(", "),d+=")"}super({name:aH,message:`${d}: Value: ${JSON.stringify(a)}.
|
|
214
|
+
Error message: ${ad(b)}`,cause:b}),this[w]=!0,this.value=a,this.context=c}static isInstance(a){return V.hasMarker(a,aI)}static wrap({value:b,cause:c,context:d}){var e,f,g;return a.isInstance(c)&&c.value===b&&(null==(e=c.context)?void 0:e.field)===(null==d?void 0:d.field)&&(null==(f=c.context)?void 0:f.entityName)===(null==d?void 0:d.entityName)&&(null==(g=c.context)?void 0:g.entityId)===(null==d?void 0:d.entityId)?c:new a({value:b,cause:c,context:d})}},aL="AI_UnsupportedFunctionalityError",aM=`vercel.ai.error.${aL}`,aN=Symbol.for(aM),aO=class extends(z=V,y=aN,z){constructor({functionality:a,message:b=`'${a}' functionality not supported.`}){super({name:aL,message:b}),this[y]=!0,this.functionality=a}static isInstance(a){return V.hasMarker(a,aM)}},aP=class extends Error{constructor(a,b){super(a),this.name="ParseError",this.type=b.type,this.field=b.field,this.value=b.value,this.line=b.line}};function aQ(a){}function aR(a,b,c){return 100===c&&97===a.charCodeAt(b+1)&&116===a.charCodeAt(b+2)&&97===a.charCodeAt(b+3)&&58===a.charCodeAt(b+4)}function aS(a,b,c){return 101===c&&118===a.charCodeAt(b+1)&&101===a.charCodeAt(b+2)&&110===a.charCodeAt(b+3)&&116===a.charCodeAt(b+4)&&58===a.charCodeAt(b+5)}var aT=class extends TransformStream{constructor({onError:a,onRetry:b,onComment:c,maxBufferSize:d}={}){let e;super({start(f){e=function(a){if("function"==typeof a)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:b=aQ,onError:c=aQ,onRetry:d=aQ,onComment:e,maxBufferSize:f}=a,g=[],h=0,i=!0,j,k="",l=0,m,n=!1;function o(){void 0!==f&&(h+k.length<=f||(n=!0,g.length=0,h=0,j=void 0,k="",l=0,m=void 0,c(new aP(`Buffered data exceeded max buffer size of ${f} characters`,{type:"max-buffer-size-exceeded"}))))}function p(a){let c=0;if(-1===a.indexOf("\r")){let d=a.indexOf(`
|
|
215
|
+
`,c);for(;-1!==d;){if(c===d){l>0&&b({id:j,event:m,data:k}),j=void 0,k="",l=0,m=void 0,c=d+1,d=a.indexOf(`
|
|
216
|
+
`,c);continue}let e=a.charCodeAt(c);if(aR(a,c,e)){let e=32===a.charCodeAt(c+5)?c+6:c+5,f=a.slice(e,d);if(0===l&&10===a.charCodeAt(d+1)){b({id:j,event:m,data:f}),j=void 0,k="",m=void 0,c=d+2,d=a.indexOf(`
|
|
217
|
+
`,c);continue}k=0===l?f:`${k}
|
|
218
|
+
${f}`,l++}else aS(a,c,e)?m=a.slice(32===a.charCodeAt(c+6)?c+7:c+6,d)||void 0:q(a,c,d);c=d+1,d=a.indexOf(`
|
|
219
|
+
`,c)}return a.slice(c)}for(;c<a.length;){let b=a.indexOf("\r",c),d=a.indexOf(`
|
|
220
|
+
`,c),e=-1;if(-1!==b&&-1!==d?e=b<d?b:d:-1!==b?e=b===a.length-1?-1:b:-1!==d&&(e=d),-1===e)break;q(a,c,e),c=e+1,13===a.charCodeAt(c-1)&&10===a.charCodeAt(c)&&c++}return a.slice(c)}function q(a,c,d){if(c===d)return void(l>0&&b({id:j,event:m,data:k}),j=void 0,k="",l=0,m=void 0);let f=a.charCodeAt(c);if(aR(a,c,f)){let b=32===a.charCodeAt(c+5)?c+6:c+5,e=a.slice(b,d);k=0===l?e:`${k}
|
|
221
|
+
${e}`,l++;return}if(aS(a,c,f)){m=a.slice(32===a.charCodeAt(c+6)?c+7:c+6,d)||void 0;return}if(105===f&&100===a.charCodeAt(c+1)&&58===a.charCodeAt(c+2)){let b=a.slice(32===a.charCodeAt(c+3)?c+4:c+3,d);j=b.includes("\0")?void 0:b;return}if(58===f){e&&e(a.slice(c,d).slice(32===a.charCodeAt(c+1)?2:1));return}let g=a.slice(c,d),h=g.indexOf(":");if(-1===h)return void r(g,"",g);let i=g.slice(0,h),n=32===g.charCodeAt(h+1)?2:1;r(i,g.slice(h+n),g)}function r(a,b,e){switch(a){case"event":m=b||void 0;break;case"data":k=0===l?b:`${k}
|
|
222
|
+
${b}`,l++;break;case"id":j=b.includes("\0")?void 0:b;break;case"retry":/^\d+$/.test(b)?d(parseInt(b,10)):c(new aP(`Invalid \`retry\` value: "${b}"`,{type:"invalid-retry",value:b,line:e}));break;default:c(new aP(`Unknown field "${a.length>20?`${a.slice(0,20)}\u2026`:a}"`,{type:"unknown-field",field:a,value:b,line:e}))}}return{feed:function(a){if(n)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(i&&(i=!1,239===a.charCodeAt(0)&&187===a.charCodeAt(1)&&191===a.charCodeAt(2)&&(a=a.slice(3))),0===g.length){let b=p(a);""!==b&&(g.push(b),h=b.length),o();return}if(-1===a.indexOf(`
|
|
223
|
+
`)&&-1===a.indexOf("\r")){g.push(a),h+=a.length,o();return}g.push(a);let b=g.join("");g.length=0,h=0;let c=p(b);""!==c&&(g.push(c),h=c.length),o()},reset:function(a={}){if(a.consume&&g.length>0){let a=g.join("");q(a,0,a.length)}i=!0,j=void 0,k="",l=0,m=void 0,g.length=0,h=0,n=!1}}}({onEvent:a=>{f.enqueue(a)},onError(b){"function"==typeof a&&a(b),("terminate"===a||"max-buffer-size-exceeded"===b.type)&&f.error(b)},onRetry:b,onComment:c,maxBufferSize:d})},transform(a){e.feed(a)}})}};function aU(...a){return a.reduce((a,b)=>P(P({},a),null!=b?b:{}),{})}async function aV(a,b){if(null==a)return Promise.resolve();let c=null==b?void 0:b.abortSignal;return new Promise((b,d)=>{if(null==c?void 0:c.aborted)return void d(aW());let e=setTimeout(()=>{f(),b()},a),f=()=>{clearTimeout(e),null==c||c.removeEventListener("abort",g)},g=()=>{f(),d(aW())};null==c||c.addEventListener("abort",g)})}function aW(){return new DOMException("Delay was aborted","AbortError")}Symbol.for("workflow-serialize"),Symbol.for("workflow-deserialize"),new TextDecoder;var{btoa:aX,atob:aY}=globalThis;function aZ(a){return Object.fromEntries([...a.headers])}function a$(a=globalThis){var b,c,d;return a.window?"runtime/browser":(null==(b=a.navigator)?void 0:b.userAgent)?`runtime/${a.navigator.userAgent.toLowerCase()}`:(null==(d=null==(c=a.process)?void 0:c.versions)?void 0:d.node)?`runtime/node.js/${a.process.version.substring(0)}`:a.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function a_(a){return(a instanceof Error||"function"==typeof DOMException&&a instanceof DOMException)&&("AbortError"===a.name||"ResponseAborted"===a.name||"TimeoutError"===a.name)}var a0=["fetch failed","failed to fetch"],a1=new Set(["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","UND_ERR_SOCKET","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"]);function a2({error:a,url:b,requestBodyValues:c}){if(a_(a))return a;if(a instanceof TypeError&&a0.includes(a.message.toLowerCase())){let d=a.cause;if(null!=d)return new Z({message:`Cannot connect to API: ${d.message}`,cause:d,url:b,requestBodyValues:c,isRetryable:!0})}let d=function(a){let b=new Set,c=a;for(;c instanceof Error&&!b.has(c);){b.add(c);let a=c;if("string"==typeof a.code&&a1.has(a.code))return a;c=c.cause}}(a);return null!=d?new Z(Z.isInstance(a)?{message:a.message,cause:a.cause,url:a.url,requestBodyValues:a.requestBodyValues,statusCode:a.statusCode,responseHeaders:a.responseHeaders,responseBody:a.responseBody,data:a.data,isRetryable:!0}:{message:`Cannot connect to API: ${a instanceof Error?a.message:d.message}`,cause:a,url:b,requestBodyValues:c,isRetryable:!0}):a}var a3="5.0.42";function a4(a,...b){let c=new Headers(function(a){if(null==a)return{};let b={};if(a instanceof Headers)a.forEach((a,c)=>{b[c.toLowerCase()]=a});else for(let[c,d]of(Array.isArray(a)||(a=Object.entries(a)),a))null!=d&&(b[c.toLowerCase()]=d);return b}(a)),d=c.get("user-agent")||"";return c.set("user-agent",[d,...b].filter(Boolean).join(" ")),Object.fromEntries(c.entries())}async function a5(a){var b;try{await (null==(b=a.body)?void 0:b.cancel())}catch(a){}}var a6="AI_DownloadError",a7=`vercel.ai.error.${a6}`,a8=Symbol.for(a7),a9=class extends(B=V,A=a8,B){constructor({url:a,statusCode:b,statusText:c,cause:d,message:e=null==d?`Failed to download ${a}: ${b} ${c}`:`Failed to download ${a}: ${d}`}){super({name:a6,message:e,cause:d}),this[A]=!0,this.url=a,this.statusCode=b,this.statusText=c}static isInstance(a){return V.hasMarker(a,a7)}};function ba(a,b){try{return new URL(a).origin===new URL(b).origin}catch(a){return!1}}function bb(a){let b=a.split(".");return 4===b.length&&b.every(a=>{let b=Number(a);return Number.isInteger(b)&&b>=0&&b<=255&&String(b)===a})}function bc(a){let[b,c,d]=a.split(".").map(Number);return 0===b||10===b||100===b&&c>=64&&c<=127||127===b||169===b&&254===c||172===b&&c>=16&&c<=31||192===b&&0===c&&0===d||192===b&&0===c&&2===d||192===b&&168===c||198===b&&(18===c||19===c)||198===b&&51===c&&100===d||203===b&&0===c&&113===d||b>=224||!1}function bd(a){let b=function(a){let b=a.toLowerCase(),c=b.indexOf("%");-1!==c&&(b=b.slice(0,c));let d=b.split("::");if(d.length>2)return null;let e=a=>{if(""===a)return[];let b=[],c=a.split(":");for(let a=0;a<c.length;a++){let d=c[a];if(d.includes(".")){if(a!==c.length-1||!bb(d))return null;let[e,f,g,h]=d.split(".").map(Number);b.push(e<<8|f,g<<8|h);continue}if(!/^[0-9a-f]{1,4}$/.test(d))return null;b.push(parseInt(d,16))}return b},f=e(d[0]);if(null===f)return null;if(2===d.length){let a=e(d[1]);if(null===a)return null;let b=8-f.length-a.length;return b<0?null:[...f,...Array(b).fill(0),...a]}return 8===f.length?f:null}(a);if(null===b)return!0;let c=a=>b.slice(0,a).every(a=>0===a);if(c(7)&&(0===b[7]||1===b[7])||(65024&b[0])==64512||(65472&b[0])==65152||(65472&b[0])==65216||(65280&b[0])==65280||8193===b[0]&&3512===b[1]||16383===b[0]&&(61440&b[1])==0)return!0;if(c(6)||c(5)&&65535===b[5]||c(4)&&65535===b[4]&&0===b[5]||100===b[0]&&65435===b[1]&&0===b[2]&&0===b[3]&&0===b[4]&&0===b[5]||100===b[0]&&65435===b[1]&&1===b[2]){let a=b[6]>>8&255,c=255&b[6],d=b[7]>>8&255,e=255&b[7];return bc(`${a}.${c}.${d}.${e}`)}return!1}async function be(){var a,b,c;let d;return(null==(a=null==(d=globalThis.process)?void 0:d.release)?void 0:a.name)!=="node"||(null==(b=d.versions)?void 0:b.bun)!=null||(null==(c=d.versions)?void 0:c.deno)!=null||"workerd"===d.title||null!=globalThis.EdgeRuntime?globalThis.fetch:null!=C?C:C=Promise.resolve().then(bf)}function bf(){let{createRequire:a}=bg("node:module"),{lookup:b}=bg("node:dns"),{Agent:c,fetch:d}=a(function a(){let b=Error.prepareStackTrace;try{Error.prepareStackTrace=(a,b)=>b;let b=Error("Capture current module path");Error.captureStackTrace(b,a);let[c]=b.stack,d=null==c?void 0:c.getFileName();if(null==d)throw Error("Unable to determine the current module path");return d}finally{Error.prepareStackTrace=b}}())("undici"),e=new c({connect:{lookup:(a,c,d)=>{b(a,Q(P({},c),{all:!0}),(b,e)=>{if(b)return void d(b);try{let[b]=e;if(null==b)throw Error(`Hostname ${a} did not resolve to an address`);for(let{address:b,family:c}of e)!function({address:a,family:b,hostname:c}){if(4===b?!bb(a)||bc(a):6!==b||bd(a))throw new a9({url:c,message:`Hostname ${c} resolved to disallowed IP address ${a}`})}({address:b,family:c,hostname:a});!0===c.all?d(null,e):d(null,b.address,b.family)}catch(a){d(a instanceof Error?a:Error(String(a)))}})}}});return(a,b)=>d(a,Q(P({},b),{dispatcher:e}))}function bg(a){var b;let c=globalThis.process,d=null==(b=null==c?void 0:c.getBuiltinModule)?void 0:b.call(c,a);if(null==d)throw Error(`Node.js built-in module ${a} is unavailable`);return d}var bh=["connection","keep-alive","te","trailer","transfer-encoding","upgrade","host","forwarded","proxy-authorization","via","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","metadata","metadata-flavor","x-aws-ec2-metadata-token","x-metadata-token","cookie","set-cookie"],bi=new Set([301,302,303,307,308]);async function bj(a){return null==a||a===globalThis.fetch?await be():a}async function bk({url:a,headers:b,abortSignal:c,maxRedirects:d=10,fetch:e,trustedOrigin:f}){var g;let h=void 0===b?void 0:function(a){let b=new Headers(a);for(let a of bh)b.delete(a);return b}(b),i=a=>{let b={signal:c,redirect:a};return void 0!==h&&(b.headers=new Headers(h)),b},j=a;for(let b=0;b<=d;b++){let b=void 0!==f&&ba(j,f);b||function(a){let b;try{b=new URL(a)}catch(b){throw new a9({url:a,message:`Invalid URL: ${a}`})}if("data:"===b.protocol)return;if("http:"!==b.protocol&&"https:"!==b.protocol)throw new a9({url:a,message:`URL scheme must be http, https, or data, got ${b.protocol}`});let c=b.hostname.toLowerCase().replace(/\.+$/,"");if(!c)throw new a9({url:a,message:"URL must have a hostname"});if("localhost"===c||c.endsWith(".local")||c.endsWith(".localhost"))throw new a9({url:a,message:`URL with hostname ${c} is not allowed`});if(c.startsWith("[")&&c.endsWith("]")){if(bd(c.slice(1,-1)))throw new a9({url:a,message:`URL with IPv6 address ${c} is not allowed`});return}if(bb(c)&&bc(c))throw new a9({url:a,message:`URL with IP address ${c} is not allowed`})}(j);let c=b&&null!=e?e:b?globalThis.fetch:await bj(e),d=await c(j,i("manual"));if("opaqueredirect"===d.type){if(!function(a=globalThis){return null!=a.window}())throw new a9({url:a,message:`Redirect from ${j} could not be validated and was blocked`});return await c(j,i("follow"))}let k=null==(g=d.headers)?void 0:g.get("location");if(bi.has(d.status)&&k){await a5(d);let a=new URL(k,j).toString();if(void 0!==h&&!ba(a,j)){let a=h.get("user-agent");h=new Headers(null==a?void 0:{"user-agent":a})}j=a;continue}return d}throw new a9({url:a,message:`Too many redirects (max ${d})`})}async function bl({response:a,url:b,maxBytes:c=0x80000000}){let d=a.headers.get("content-length");if(null!=d){let e=parseInt(d,10);if(!isNaN(e)&&e>c)throw await a5(a),new a9({url:b,message:`Download of ${b} exceeded maximum size of ${c} bytes (Content-Length: ${e}).`})}let e=a.body;if(null==e)return new Uint8Array(0);let f=e.getReader(),g=[],h=0;try{for(;;){let{done:a,value:d}=await f.read();if(a)break;if((h+=d.length)>c)throw new a9({url:b,message:`Download of ${b} exceeded maximum size of ${c} bytes.`});g.push(d)}}finally{try{await f.cancel()}catch(a){}finally{f.releaseLock()}}let i=new Uint8Array(h),j=0;for(let a of g)i.set(a,j),j+=a.length;return i}var bm=(({prefix:a,size:b=16,alphabet:c="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:d="-"}={})=>{let e=()=>{let a=c.length,d=Array(b);for(let e=0;e<b;e++)d[e]=c[Math.random()*a|0];return d.join("")};if(null==a)return e;if(c.includes(d))throw new ah({argument:"separator",message:`The separator "${d}" must not be part of the alphabet "${c}".`});return()=>`${a}${d}${e()}`})(),bn=async({url:a,headers:b={},successfulResponseHandler:c,failedResponseHandler:d,abortSignal:e,fetch:f,validateUrl:g,credentialedOrigin:h,trustedOrigin:i})=>{try{let j=null!=f?f:globalThis.fetch,k=void 0===h||ba(a,h)?b:{},l=a4(k,`ai-sdk/provider-utils/${a3}`,a$()),m=g?await bk({url:a,headers:l,abortSignal:e,fetch:f,trustedOrigin:i}):await j(a,{method:"GET",headers:l,signal:e}),n=aZ(m);if(!m.ok){let b;try{b=await d({response:m,url:a,requestBodyValues:{}})}catch(b){if(a_(b)||Z.isInstance(b))throw b;throw new Z({message:"Failed to process error response",cause:b,statusCode:m.status,url:a,responseHeaders:n,requestBodyValues:{}})}throw b.value}try{return await c({response:m,url:a,requestBodyValues:{}})}catch(b){if(b instanceof Error&&(a_(b)||Z.isInstance(b)))throw b;throw new Z({message:"Failed to process successful response",cause:b,statusCode:m.status,url:a,responseHeaders:n,requestBodyValues:{}})}}catch(b){throw a2({error:b,url:a,requestBodyValues:{}})}},bo=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,bp=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function bq(a){let b=JSON.parse(a);return null===b||"object"!=typeof b||!1===bo.test(a)&&!1===bp.test(a)?b:function(a){let b=[a];for(;b.length;){let a=b;for(let c of(b=[],a)){if(Object.prototype.hasOwnProperty.call(c,"__proto__")||Object.prototype.hasOwnProperty.call(c,"constructor")&&null!==c.constructor&&"object"==typeof c.constructor&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let a in c){let d=c[a];d&&"object"==typeof d&&b.push(d)}}}return a}(b)}function br(a){let{stackTraceLimit:b}=Error;try{Error.stackTraceLimit=0}catch(b){return bq(a)}try{return bq(a)}finally{Error.stackTraceLimit=b}}function bs(a){if("object"===a.type||Array.isArray(a.type)&&a.type.includes("object")){let{additionalProperties:b}=a;a.additionalProperties=null!=b&&"boolean"!=typeof b&&bt(b);let{properties:c}=a;if(null!=c)for(let a of Object.keys(c))c[a]=bt(c[a])}null!=a.items&&(a.items=Array.isArray(a.items)?a.items.map(bt):bt(a.items)),null!=a.anyOf&&(a.anyOf=a.anyOf.map(bt)),null!=a.allOf&&(a.allOf=a.allOf.map(bt)),null!=a.oneOf&&(a.oneOf=a.oneOf.map(bt));let{definitions:b}=a;if(null!=b)for(let a of Object.keys(b))b[a]=bt(b[a]);return a}function bt(a){return"boolean"==typeof a?a:bs(a)}var bu=Symbol("Let zodToJsonSchema decide on which parser to use"),bv={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"};function bw(a,b){return bR(a.type._def,b)}var bx=void 0,by=/^[cC][^\s-]{8,}$/,bz=/^[0-9a-z]+$/,bA=/^[0-9A-HJKMNP-TV-Z]{26}$/,bB=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,bC=()=>(void 0===bx&&(bx=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),bx),bD=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,bE=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bF=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,bG=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,bH=/^[a-zA-Z0-9_-]{21}$/,bI=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function bJ(a,b){let c={type:"string"};if(a.checks)for(let d of a.checks)switch(d.kind){case"min":c.minLength="number"==typeof c.minLength?Math.max(c.minLength,d.value):d.value;break;case"max":c.maxLength="number"==typeof c.maxLength?Math.min(c.maxLength,d.value):d.value;break;case"email":switch(b.emailStrategy){case"format:email":bM(c,"email",d.message,b);break;case"format:idn-email":bM(c,"idn-email",d.message,b);break;case"pattern:zod":bN(c,bB,d.message,b)}break;case"url":bM(c,"uri",d.message,b);break;case"uuid":bM(c,"uuid",d.message,b);break;case"regex":bN(c,d.regex,d.message,b);break;case"cuid":bN(c,by,d.message,b);break;case"cuid2":bN(c,bz,d.message,b);break;case"startsWith":bN(c,RegExp(`^${bK(d.value,b)}`),d.message,b);break;case"endsWith":bN(c,RegExp(`${bK(d.value,b)}$`),d.message,b);break;case"datetime":bM(c,"date-time",d.message,b);break;case"date":bM(c,"date",d.message,b);break;case"time":bM(c,"time",d.message,b);break;case"duration":bM(c,"duration",d.message,b);break;case"length":c.minLength="number"==typeof c.minLength?Math.max(c.minLength,d.value):d.value,c.maxLength="number"==typeof c.maxLength?Math.min(c.maxLength,d.value):d.value;break;case"includes":bN(c,RegExp(bK(d.value,b)),d.message,b);break;case"ip":"v6"!==d.version&&bM(c,"ipv4",d.message,b),"v4"!==d.version&&bM(c,"ipv6",d.message,b);break;case"base64url":bN(c,bG,d.message,b);break;case"jwt":bN(c,bI,d.message,b);break;case"cidr":"v6"!==d.version&&bN(c,bD,d.message,b),"v4"!==d.version&&bN(c,bE,d.message,b);break;case"emoji":bN(c,bC(),d.message,b);break;case"ulid":bN(c,bA,d.message,b);break;case"base64":switch(b.base64Strategy){case"format:binary":bM(c,"binary",d.message,b);break;case"contentEncoding:base64":c.contentEncoding="base64";break;case"pattern:zod":bN(c,bF,d.message,b)}break;case"nanoid":bN(c,bH,d.message,b)}return c}function bK(a,b){return"escape"===b.patternStrategy?function(a){let b="";for(let c=0;c<a.length;c++)bL.has(a[c])||(b+="\\"),b+=a[c];return b}(a):a}var bL=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function bM(a,b,c,d){var e;a.format||(null==(e=a.anyOf)?void 0:e.some(a=>a.format))?(a.anyOf||(a.anyOf=[]),a.format&&(a.anyOf.push({format:a.format}),delete a.format),a.anyOf.push(P({format:b},c&&d.errorMessages&&{errorMessage:{format:c}}))):a.format=b}function bN(a,b,c,d){var e;a.pattern||(null==(e=a.allOf)?void 0:e.some(a=>a.pattern))?(a.allOf||(a.allOf=[]),a.pattern&&(a.allOf.push({pattern:a.pattern}),delete a.pattern),a.allOf.push(P({pattern:bO(b,d)},c&&d.errorMessages&&{errorMessage:{pattern:c}}))):a.pattern=bO(b,d)}function bO(a,b){var c;if(!b.applyRegexFlags||!a.flags)return a.source;let d={i:a.flags.includes("i"),m:a.flags.includes("m"),s:a.flags.includes("s")},e=d.i?a.source.toLowerCase():a.source,f="",g=!1,h=!1,i=!1;for(let a=0;a<e.length;a++){if(g){f+=e[a],g=!1;continue}if(d.i){if(h){if(e[a].match(/[a-z]/)){i?(f+=e[a],f+=`${e[a-2]}-${e[a]}`.toUpperCase(),i=!1):"-"===e[a+1]&&(null==(c=e[a+2])?void 0:c.match(/[a-z]/))?(f+=e[a],i=!0):f+=`${e[a]}${e[a].toUpperCase()}`;continue}}else if(e[a].match(/[a-z]/)){f+=`[${e[a]}${e[a].toUpperCase()}]`;continue}}if(d.m){if("^"===e[a]){f+=`(^|(?<=[\r
|
|
224
|
+
]))`;continue}else if("$"===e[a]){f+=`($|(?=[\r
|
|
225
|
+
]))`;continue}}if(d.s&&"."===e[a]){f+=h?`${e[a]}\r
|
|
226
|
+
`:`[${e[a]}\r
|
|
227
|
+
]`;continue}f+=e[a],"\\"===e[a]?g=!0:h&&"]"===e[a]?h=!1:h||"["!==e[a]||(h=!0)}try{new RegExp(f)}catch(c){return console.warn(`Could not convert regex pattern at ${b.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),a.source}return f}function bP(a,b){var c,d,e,f,g,h;let i={type:"object",additionalProperties:null!=(c=bR(a.valueType._def,Q(P({},b),{currentPath:[...b.currentPath,"additionalProperties"]})))?c:b.allowedAdditionalProperties};if((null==(d=a.keyType)?void 0:d._def.typeName)==="ZodString"&&(null==(e=a.keyType._def.checks)?void 0:e.length)){let c=bJ(a.keyType._def,b),{type:d}=c,e=R(c,["type"]);return Q(P({},i),{propertyNames:e})}if((null==(f=a.keyType)?void 0:f._def.typeName)==="ZodEnum")return Q(P({},i),{propertyNames:{enum:a.keyType._def.values}});if((null==(g=a.keyType)?void 0:g._def.typeName)==="ZodBranded"&&"ZodString"===a.keyType._def.type._def.typeName&&(null==(h=a.keyType._def.type._def.checks)?void 0:h.length)){let c=bw(a.keyType._def,b),{type:d}=c,e=R(c,["type"]);return Q(P({},i),{propertyNames:e})}return i}var bQ={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bR(a,b,c=!1){var d;let e=b.seen.get(a);if(b.override){let f=null==(d=b.override)?void 0:d.call(b,a,b,e,c);if(f!==bu)return f}if(e&&!c){let a=bS(e,b);if(void 0!==a)return a}let f={def:a,path:b.currentPath,jsonSchema:void 0};b.seen.set(a,f);let g=((a,b,c)=>{var d,e,f,g,h,i;switch(b){case"ZodString":return bJ(a,c);case"ZodNumber":let j={type:"number"};if(!a.checks)return j;for(let b of a.checks)switch(b.kind){case"int":j.type="integer";break;case"min":b.inclusive?j.minimum=b.value:j.exclusiveMinimum=b.value;break;case"max":b.inclusive?j.maximum=b.value:j.exclusiveMaximum=b.value;break;case"multipleOf":j.multipleOf=b.value}return j;case"ZodObject":return function(a,b){let c={type:"object",properties:{}},d=[],e=a.shape();for(let a in e){let f=e[a];if(void 0===f||void 0===f._def)continue;let g=function(a){try{return a.isOptional()}catch(a){return!0}}(f),h=bR(f._def,Q(P({},b),{currentPath:[...b.currentPath,"properties",a],propertyPath:[...b.currentPath,"properties",a]}));void 0!==h&&(c.properties[a]=h,g||d.push(a))}d.length&&(c.required=d);let f=function(a,b){if("ZodNever"!==a.catchall._def.typeName)return bR(a.catchall._def,Q(P({},b),{currentPath:[...b.currentPath,"additionalProperties"]}));switch(a.unknownKeys){case"passthrough":return b.allowedAdditionalProperties;case"strict":return b.rejectedAdditionalProperties;case"strip":return"strict"===b.removeAdditionalStrategy?b.allowedAdditionalProperties:b.rejectedAdditionalProperties}}(a,b);return void 0!==f&&(c.additionalProperties=f),c}(a,c);case"ZodBigInt":let k={type:"integer",format:"int64"};if(!a.checks)return k;for(let b of a.checks)switch(b.kind){case"min":b.inclusive?k.minimum=b.value:k.exclusiveMinimum=b.value;break;case"max":b.inclusive?k.maximum=b.value:k.exclusiveMaximum=b.value;break;case"multipleOf":k.multipleOf=b.value}return k;case"ZodBoolean":return{type:"boolean"};case"ZodDate":return function a(b,c,d){let e=null!=d?d:c.dateStrategy;if(Array.isArray(e))return{anyOf:e.map(d=>a(b,c,d))};switch(e){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var f=b;let g={type:"integer",format:"unix-time"};for(let a of f.checks)switch(a.kind){case"min":g.minimum=a.value;break;case"max":g.maximum=a.value}return g}}(a,c);case"ZodUndefined":case"ZodNaN":case"ZodNever":return{not:{}};case"ZodNull":return{type:"null"};case"ZodArray":let l;return l={type:"array"},(null==(f=a.type)?void 0:f._def)&&(null==(h=null==(g=a.type)?void 0:g._def)?void 0:h.typeName)!=="ZodAny"&&(l.items=bR(a.type._def,Q(P({},c),{currentPath:[...c.currentPath,"items"]}))),a.minLength&&(l.minItems=a.minLength.value),a.maxLength&&(l.maxItems=a.maxLength.value),a.exactLength&&(l.minItems=a.exactLength.value,l.maxItems=a.exactLength.value),l;case"ZodUnion":case"ZodDiscriminatedUnion":let m,n=a.options instanceof Map?Array.from(a.options.values()):a.options;if(n.every(a=>a._def.typeName in bQ&&(!a._def.checks||!a._def.checks.length))){let a=n.reduce((a,b)=>{let c=bQ[b._def.typeName];return c&&!a.includes(c)?[...a,c]:a},[]);return{type:a.length>1?a:a[0]}}if(n.every(a=>"ZodLiteral"===a._def.typeName&&!a.description)){let a=n.reduce((a,b)=>{let c=typeof b._def.value;switch(c){case"string":case"number":case"boolean":return[...a,c];case"bigint":return[...a,"integer"];case"object":if(null===b._def.value)return[...a,"null"];default:return a}},[]);if(a.length===n.length){let b=a.filter((a,b,c)=>c.indexOf(a)===b);return{type:b.length>1?b:b[0],enum:n.reduce((a,b)=>a.includes(b._def.value)?a:[...a,b._def.value],[])}}}else if(n.every(a=>"ZodEnum"===a._def.typeName))return{type:"string",enum:n.reduce((a,b)=>[...a,...b._def.values.filter(b=>!a.includes(b))],[])};return d=a,e=c,(m=(d.options instanceof Map?Array.from(d.options.values()):d.options).map((a,b)=>bR(a._def,Q(P({},e),{currentPath:[...e.currentPath,"anyOf",`${b}`]}))).filter(a=>!!a&&(!e.strictUnions||"object"==typeof a&&Object.keys(a).length>0))).length?{anyOf:m}:void 0;case"ZodIntersection":let o,p;return o=[bR(a.left._def,Q(P({},c),{currentPath:[...c.currentPath,"allOf","0"]})),bR(a.right._def,Q(P({},c),{currentPath:[...c.currentPath,"allOf","1"]}))].filter(a=>!!a),p=[],o.forEach(a=>{if((!("type"in a)||"string"!==a.type)&&"allOf"in a)p.push(...a.allOf);else{let b=a;if("additionalProperties"in a&&!1===a.additionalProperties){let{additionalProperties:c}=a;b=R(a,["additionalProperties"])}p.push(b)}}),p.length?{allOf:p}:void 0;case"ZodTuple":return a.rest?{type:"array",minItems:a.items.length,items:a.items.map((a,b)=>bR(a._def,Q(P({},c),{currentPath:[...c.currentPath,"items",`${b}`]}))).reduce((a,b)=>void 0===b?a:[...a,b],[]),additionalItems:bR(a.rest._def,Q(P({},c),{currentPath:[...c.currentPath,"additionalItems"]}))}:{type:"array",minItems:a.items.length,maxItems:a.items.length,items:a.items.map((a,b)=>bR(a._def,Q(P({},c),{currentPath:[...c.currentPath,"items",`${b}`]}))).reduce((a,b)=>void 0===b?a:[...a,b],[])};case"ZodRecord":return bP(a,c);case"ZodLiteral":let q;return"bigint"!=(q=typeof a.value)&&"number"!==q&&"boolean"!==q&&"string"!==q?{type:Array.isArray(a.value)?"array":"object"}:{type:"bigint"===q?"integer":q,const:a.value};case"ZodEnum":return{type:"string",enum:Array.from(a.values)};case"ZodNativeEnum":let r,s,t;return r=a.values,{type:1===(t=Array.from(new Set((s=Object.keys(a.values).filter(a=>"number"!=typeof r[r[a]]).map(a=>r[a])).map(a=>typeof a)))).length?"string"===t[0]?"string":"number":["string","number"],enum:s};case"ZodNullable":if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(a.innerType._def.typeName)&&(!a.innerType._def.checks||!a.innerType._def.checks.length))return{type:[bQ[a.innerType._def.typeName],"null"]};let u=bR(a.innerType._def,Q(P({},c),{currentPath:[...c.currentPath,"anyOf","0"]}));return u&&{anyOf:[u,{type:"null"}]};case"ZodOptional":if(c.currentPath.toString()===(null==(i=c.propertyPath)?void 0:i.toString()))return bR(a.innerType._def,c);let v=bR(a.innerType._def,Q(P({},c),{currentPath:[...c.currentPath,"anyOf","1"]}));return v?{anyOf:[{not:{}},v]}:{};case"ZodMap":if("record"===c.mapStrategy)return bP(a,c);return{type:"array",maxItems:125,items:{type:"array",items:[bR(a.keyType._def,Q(P({},c),{currentPath:[...c.currentPath,"items","items","0"]}))||{},bR(a.valueType._def,Q(P({},c),{currentPath:[...c.currentPath,"items","items","1"]}))||{}],minItems:2,maxItems:2}};case"ZodSet":let w;return w={type:"array",uniqueItems:!0,items:bR(a.valueType._def,Q(P({},c),{currentPath:[...c.currentPath,"items"]}))},a.minSize&&(w.minItems=a.minSize.value),a.maxSize&&(w.maxItems=a.maxSize.value),w;case"ZodLazy":return()=>a.getter()._def;case"ZodPromise":return bR(a.type._def,c);case"ZodEffects":return"input"===c.effectStrategy?bR(a.schema._def,c):{};case"ZodAny":case"ZodUnknown":return{};case"ZodDefault":return Q(P({},bR(a.innerType._def,c)),{default:a.defaultValue()});case"ZodBranded":return bw(a,c);case"ZodReadonly":case"ZodCatch":return bR(a.innerType._def,c);case"ZodPipeline":if("input"===c.pipeStrategy)return bR(a.in._def,c);if("output"===c.pipeStrategy)return bR(a.out._def,c);let x=bR(a.in._def,Q(P({},c),{currentPath:[...c.currentPath,"allOf","0"]})),y=bR(a.out._def,Q(P({},c),{currentPath:[...c.currentPath,"allOf",x?"1":"0"]}));return{allOf:[x,y].filter(a=>void 0!==a)};default:return}})(a,a.typeName,b),h="function"==typeof g?bR(g(),b):g;if(h&&bT(a,b,h),b.postProcess){let c=b.postProcess(h,a,b);return f.jsonSchema=h,c}return f.jsonSchema=h,h}var bS=(a,b)=>{switch(b.$refStrategy){case"root":return{$ref:a.path.join("/")};case"relative":return{$ref:((a,b)=>{let c=0;for(;c<a.length&&c<b.length&&a[c]===b[c];c++);return[(a.length-c).toString(),...b.slice(c)].join("/")})(b.currentPath,a.path)};case"none":case"seen":if(a.path.length<b.currentPath.length&&a.path.every((a,c)=>b.currentPath[c]===a))return console.warn(`Recursive reference detected at ${b.currentPath.join("/")}! Defaulting to any`),{};return"seen"===b.$refStrategy?{}:void 0}},bT=(a,b,c)=>(a.description&&(c.description=a.description),c),bU=Symbol.for("vercel.ai.schema");function bV(a,{validate:b}={}){return{[bU]:!0,_type:void 0,get jsonSchema(){return"function"==typeof a&&(a=a()),a},validate:b}}async function bW({value:a,schema:b,context:c}){let d=await bX({value:a,schema:b,context:c});if(!d.success)throw aK.wrap({value:a,cause:d.error,context:c});return d.value}async function bX({value:a,schema:b,context:c}){var d;let e=null==b?bV({type:"object",properties:{},additionalProperties:!1}):"object"==typeof b&&null!==b&&bU in b&&!0===b[bU]&&"jsonSchema"in b&&"validate"in b?b:"~standard"in b?"zod"===b["~standard"].vendor?function(a){var b,c;let d;if("_zod"in a){let c;return c=(b=void 0,false),bV(()=>bs((0,F.toJSONSchema)(a,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async b=>{let c=await (0,E.safeParseAsync)(a,b);return c.success?{success:!0,value:c.data}:{success:!1,error:c.error}}})}return d=(c=void 0,false),bV(()=>((a,b)=>{var c;let d,e,f=(e=void 0!==(d="string"==typeof b?Q(P({},bv),{name:b}):P(P({},bv),b)).name?[...d.basePath,d.definitionPath,d.name]:d.basePath,Q(P({},d),{currentPath:e,propertyPath:void 0,seen:new Map(Object.entries(d.definitions).map(([a,b])=>[b._def,{def:b._def,path:[...d.basePath,d.definitionPath,a],jsonSchema:void 0}]))})),g="object"==typeof b&&b.definitions?Object.entries(b.definitions).reduce((a,[b,c])=>{var d;return Q(P({},a),{[b]:null!=(d=bR(c._def,Q(P({},f),{currentPath:[...f.basePath,f.definitionPath,b]}),!0))?d:{}})},{}):void 0,h="string"==typeof b?b:(null==b?void 0:b.nameStrategy)==="title"||null==b?void 0:b.name,i=null!=(c=bR(a._def,void 0===h?f:Q(P({},f),{currentPath:[...f.basePath,f.definitionPath,h]}),!1))?c:{},j="object"==typeof b&&void 0!==b.name&&"title"===b.nameStrategy?b.name:void 0;void 0!==j&&(i.title=j);let k=void 0===h?g?Q(P({},i),{[f.definitionPath]:g}):i:{$ref:[..."relative"===f.$refStrategy?[]:f.basePath,f.definitionPath,h].join("/"),[f.definitionPath]:Q(P({},g),{[h]:i})};return k.$schema="http://json-schema.org/draft-07/schema#",k})(a,{$refStrategy:d?"root":"none"}),{validate:async b=>{let c=await a.safeParseAsync(b);return c.success?{success:!0,value:c.data}:{success:!1,error:c.error}}})}(b):(d=b,bV(()=>{if(null==d["~standard"].jsonSchema)throw Error(`Standard schema vendor '${d["~standard"].vendor}' does not support JSON Schema conversion.`);return bs(d["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async a=>{let b=await d["~standard"].validate(a);return"value"in b?{success:!0,value:b.value}:{success:!1,error:new aK({value:a,cause:b.issues})}}})):b();try{if(null==e.validate)return{success:!0,value:a,rawValue:a};let b=await e.validate(a);if(b.success)return{success:!0,value:b.value,rawValue:a};return{success:!1,error:aK.wrap({value:a,cause:b.error,context:c}),rawValue:a}}catch(b){return{success:!1,error:aK.wrap({value:a,cause:b,context:c}),rawValue:a}}}async function bY({text:a,schema:b}){try{let c=br(a);if(null==b)return c;return await bW({value:c,schema:b})}catch(b){if(at.isInstance(b)||aK.isInstance(b))throw b;throw new at({text:a,cause:b})}}async function bZ({text:a,schema:b}){try{let c=br(a);if(null==b)return{success:!0,value:c,rawValue:c};return await bX({value:c,schema:b})}catch(b){return{success:!1,error:at.isInstance(b)?b:new at({text:a,cause:b}),rawValue:void 0}}}function b$(a){try{return br(a),!0}catch(a){return!1}}async function b_({provider:a,providerOptions:b,schema:c}){if((null==b?void 0:b[a])==null)return;let d=await bX({value:b[a],schema:c});if(!d.success)throw new ah({argument:"providerOptions",message:`invalid ${a} provider options`,cause:d.error});return d.value}var b0=()=>globalThis.fetch,b1=async({url:a,headers:b,body:c,failedResponseHandler:d,successfulResponseHandler:e,abortSignal:f,fetch:g})=>await b2({url:a,headers:P({"Content-Type":"application/json"},b),body:{content:JSON.stringify(c),values:c},failedResponseHandler:d,successfulResponseHandler:e,abortSignal:f,fetch:g}),b2=async({url:a,headers:b={},body:c,successfulResponseHandler:d,failedResponseHandler:e,abortSignal:f,fetch:g=b0()})=>{try{let h=await g(a,{method:"POST",headers:a4(b,`ai-sdk/provider-utils/${a3}`,a$()),body:c.content,signal:f}),i=aZ(h);if(!h.ok){let b;try{b=await e({response:h,url:a,requestBodyValues:c.values})}catch(b){if(a_(b)||Z.isInstance(b))throw b;throw new Z({message:"Failed to process error response",cause:b,statusCode:h.status,url:a,responseHeaders:i,requestBodyValues:c.values})}throw b.value}try{return await d({response:h,url:a,requestBodyValues:c.values})}catch(b){if(b instanceof Error&&(a_(b)||Z.isInstance(b)))throw b;throw new Z({message:"Failed to process successful response",cause:b,statusCode:h.status,url:a,responseHeaders:i,requestBodyValues:c.values})}}catch(b){throw a2({error:b,url:a,requestBodyValues:c.values})}},b3=new TextDecoder;async function b4({response:a,url:b}){return b3.decode(await bl({response:a,url:b}))}var b5=a=>async({response:b,url:c,requestBodyValues:d})=>{let e=aZ(b);if(null==b.body)throw new ab({});return{responseHeaders:e,value:function({stream:a,schema:b}){return a.pipeThrough(new TextDecoderStream).pipeThrough(new aT).pipeThrough(new TransformStream({async transform({data:a},c){"[DONE]"!==a&&c.enqueue(await bZ({text:a,schema:b}))}}))}({stream:function({stream:a,url:b,requestBodyValues:c,statusCode:d,responseHeaders:e}){let f=a.getReader(),g=!1,h=()=>{g||(f.releaseLock(),g=!0)};return new ReadableStream({async pull(a){try{let{done:b,value:c}=await f.read();b?(h(),a.close()):a.enqueue(c)}catch(f){if(h(),a_(f))return void a.error(f);a.error(a2({error:new Z({message:"Failed to process successful response",cause:f,statusCode:d,url:b,responseHeaders:e,requestBodyValues:c}),url:b,requestBodyValues:c}))}},async cancel(a){try{await f.cancel(a)}finally{h()}}})}({stream:b.body,url:c,requestBodyValues:d,statusCode:b.status,responseHeaders:e}),schema:a})}},b6=a=>async({response:b,url:c,requestBodyValues:d})=>{let e=await b4({response:b,url:c}),f=await bZ({text:e,schema:a}),g=aZ(b);if(!f.success)throw new Z({message:"Invalid JSON response",cause:f.error,statusCode:b.status,responseHeaders:g,responseBody:e,url:c,requestBodyValues:d});return{responseHeaders:g,value:f.value,rawValue:f.rawValue}},b7=Symbol.for("vercel.ai.error.AI_SerializationError");function b8(a){return null==a?void 0:a.replace(/\/$/,"")}function b9(a){return null!=a}var ca=((b=ca||{}).Unknown="unknown",b.OpenAIResponsesV1="openai-responses-v1",b.AzureOpenAIResponsesV1="azure-openai-responses-v1",b.XAIResponsesV1="xai-responses-v1",b.AnthropicClaudeV1="anthropic-claude-v1",b.GoogleGeminiV1="google-gemini-v1",b),cb=G.z.object({id:G.z.string().nullish(),format:G.z.enum(ca).nullish(),index:G.z.number().optional()}).loose(),cc=G.z.object({type:G.z.literal("reasoning.summary"),summary:G.z.string()}).extend(cb.shape),cd=G.z.object({type:G.z.literal("reasoning.encrypted"),data:G.z.string()}).extend(cb.shape),ce=G.z.object({type:G.z.literal("reasoning.text"),text:G.z.string().nullish(),signature:G.z.string().nullish()}).extend(cb.shape),cf=G.z.union([cc,cd,ce]),cg=G.z.union([cf,G.z.unknown().transform(()=>null)]),ch=G.z.array(cg).transform(a=>a.filter(a=>!!a));G.z.union([G.z.object({delta:G.z.object({reasoning_details:G.z.array(cg)})}).transform(a=>a.delta.reasoning_details.filter(b9)),G.z.object({message:G.z.object({reasoning_details:G.z.array(cg)})}).transform(a=>a.message.reasoning_details.filter(b9)),G.z.object({text:G.z.string(),reasoning_details:G.z.array(cg)}).transform(a=>a.reasoning_details.filter(b9))]);var ci=G.z.object({error:G.z.object({code:G.z.union([G.z.string(),G.z.number()]).nullable().optional().default(null),message:G.z.string(),type:G.z.string().nullable().optional().default(null),param:G.z.any().nullable().optional().default(null)}).passthrough()}).passthrough(),cj=(({errorSchema:a,errorToMessage:b,isRetryable:c})=>async({response:d,url:e,requestBodyValues:f})=>{let g=await b4({response:d,url:e}),h=aZ(d);if(""===g.trim())return{responseHeaders:h,value:new Z({message:d.statusText,url:e,requestBodyValues:f,statusCode:d.status,responseHeaders:h,responseBody:g,isRetryable:null==c?void 0:c(d)})};try{let i=await bY({text:g,schema:a});return{responseHeaders:h,value:new Z({message:b(i),url:e,requestBodyValues:f,statusCode:d.status,responseHeaders:h,responseBody:g,data:i,isRetryable:null==c?void 0:c(d,i)})}}catch(a){return{responseHeaders:h,value:new Z({message:d.statusText,url:e,requestBodyValues:f,statusCode:d.status,responseHeaders:h,responseBody:g,isRetryable:null==c?void 0:c(d)})}}})({errorSchema:ci,errorToMessage:function(a){let b=a.error.metadata;if(!b)return a.error.message;let c=[];"string"==typeof b.provider_name&&b.provider_name&&c.push(`[${b.provider_name}]`);let d=function a(b){if("string"==typeof b)try{let c=JSON.parse(b);if("object"==typeof c&&null!==c)return a(c);return b}catch(a){return b}if("object"==typeof b&&null!==b)for(let c of["message","error","detail","details","msg"]){let d=b[c];if("string"==typeof d&&d.length>0)return d;if("object"==typeof d&&null!==d){let b=a(d);if(b)return b}}}(b.raw);return d&&d!==a.error.message?c.push(d):c.push(a.error.message),c.join(" ")}}),ck=G.z.object({type:G.z.literal("file"),file:G.z.object({hash:G.z.string(),name:G.z.string(),content:G.z.array(G.z.object({type:G.z.string(),text:G.z.string().optional()}).catchall(G.z.any())).optional()}).catchall(G.z.any())}).catchall(G.z.any()),cl=G.z.object({provider:G.z.string(),reasoning_details:G.z.array(cf).optional(),annotations:G.z.array(ck).optional(),usage:G.z.object({promptTokens:G.z.number(),promptTokensDetails:G.z.object({cachedTokens:G.z.number()}).catchall(G.z.any()).optional(),completionTokens:G.z.number(),completionTokensDetails:G.z.object({reasoningTokens:G.z.number()}).catchall(G.z.any()).optional(),totalTokens:G.z.number(),cost:G.z.number().optional(),costDetails:G.z.object({upstreamInferenceCost:G.z.number()}).catchall(G.z.any()).optional()}).catchall(G.z.any())}).catchall(G.z.any()),cm=G.z.object({openrouter:G.z.object({reasoning_details:ch.optional(),annotations:G.z.array(ck).optional()}).optional()}).optional();function cn(a){var b,c,d,e,f,g,h,i;let j=null!=(b=a.prompt_tokens)?b:0,k=null!=(c=a.completion_tokens)?c:0,l=null!=(e=null==(d=a.prompt_tokens_details)?void 0:d.cached_tokens)?e:0,m=null!=(g=null==(f=a.prompt_tokens_details)?void 0:f.cache_write_tokens)?g:void 0,n=null!=(i=null==(h=a.completion_tokens_details)?void 0:h.reasoning_tokens)?i:0;return{inputTokens:{total:j,noCache:j-l,cacheRead:l,cacheWrite:m},outputTokens:{total:k,text:k-n,reasoning:n},raw:a}}function co(){return{inputTokens:{total:0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:0,text:void 0,reasoning:void 0},raw:void 0}}function cp(a){return{unified:function(a){switch(a){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}(a),raw:null!=a?a:void 0}}function cq(a,b){return{unified:a,raw:b}}function cr(a,b){let c=a.getReader();return new ReadableStream({async pull(a){try{let{done:b,value:d}=await c.read();b?a.close():a.enqueue(d)}catch(d){b(d),c.cancel().catch(()=>{}),a.close()}},cancel(a){c.cancel(a)}})}var cs=class{constructor(){((a,b,c)=>b.has(a)?N("Cannot add the same private member more than once"):b instanceof WeakSet?b.add(a):b.set(a,c))(this,D,new Set)}upsert(a){let b=this.getCanonicalKey(a);return!(null===b||S(this,D).has(b))&&(S(this,D).add(b),!0)}getCanonicalKey(a){switch(a.type){case"reasoning.summary":return a.summary;case"reasoning.encrypted":if(a.id)return a.id;return a.data;case"reasoning.text":if(a.text)return a.text;if(a.signature)return a.signature;return null;default:return null}}};D=new WeakMap;var ct=["wav","mp3","aiff","aac","ogg","flac","m4a","pcm16","pcm24"];function cu({url:a,protocols:b}){try{let c=new URL(a);return b.has(c.protocol)}catch(a){return!1}}function cv({data:a,mediaType:b,defaultMediaType:c}){if(a instanceof Uint8Array){let d=function(a){let b=[];for(let c=0;c<a.length;c+=4096)b.push(String.fromCodePoint(...a.subarray(c,c+4096)));return aX(b.join(""))}(a);return`data:${null!=b?b:c};base64,${d}`}let d=a.toString();return cu({url:d,protocols:new Set(["http:","https:"])})||d.startsWith("data:")?d:`data:${null!=b?b:c};base64,${d}`}function cw({part:a,defaultMediaType:b}){return cx({data:a.data,mediaType:a.mediaType,defaultMediaType:b})}function cx({data:a,mediaType:b,defaultMediaType:c}){switch(a.type){case"data":return cv({data:a.data,mediaType:b,defaultMediaType:c});case"url":{let b=a.url.toString();if(b.startsWith("data:")||cu({url:b,protocols:new Set(["http:","https:"])}))return b;throw Error("Only http(s) and data: file URLs are supported by OpenRouter")}case"text":return cv({data:new TextEncoder().encode(a.text),mediaType:null!=b?b:"text/plain",defaultMediaType:c});case"reference":throw Error("Provider file references are not supported by OpenRouter")}return cv({data:a,mediaType:b,defaultMediaType:c})}function cy(a,b){var c;let d=a.match(/^data:([^;]+)/);return d&&null!=(c=d[1])?c:b}function cz(a){let b=a.match(/^data:[^;]*;base64,(.+)$/);return b?b[1]:a}var cA={mpeg:"mp3",mp3:"mp3","x-wav":"wav",wave:"wav",wav:"wav",ogg:"ogg",vorbis:"ogg",aac:"aac","x-aac":"aac",m4a:"m4a","x-m4a":"m4a",mp4:"m4a",aiff:"aiff","x-aiff":"aiff",flac:"flac","x-flac":"flac",pcm16:"pcm16",pcm24:"pcm24"};function cB(a){var b,c,d;let e=null==a?void 0:a.anthropic,f=null==a?void 0:a.openrouter;return null!=(d=null!=(c=null!=(b=null==f?void 0:f.cacheControl)?b:null==f?void 0:f.cache_control)?c:null==e?void 0:e.cacheControl)?d:null==e?void 0:e.cache_control}G.z.union([G.z.literal("auto"),G.z.literal("none"),G.z.literal("required"),G.z.object({type:G.z.literal("function"),function:G.z.object({name:G.z.string()})})]);var cC=G.z.object({type:G.z.literal("image_url"),image_url:G.z.object({url:G.z.string()}).passthrough()}).passthrough(),cD=G.z.union([cC,G.z.unknown().transform(()=>null)]),cE=G.z.array(cD).transform(a=>a.filter(a=>!!a)),cF=G.z.object({id:G.z.string().optional(),model:G.z.string().optional(),provider:G.z.string().optional(),usage:G.z.object({prompt_tokens:G.z.number(),prompt_tokens_details:G.z.object({cached_tokens:G.z.number(),cache_write_tokens:G.z.number().nullish()}).passthrough().nullish(),completion_tokens:G.z.number(),completion_tokens_details:G.z.object({reasoning_tokens:G.z.number()}).passthrough().nullish(),total_tokens:G.z.number(),cost:G.z.number().optional(),cost_details:G.z.object({upstream_inference_cost:G.z.number().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),cG=G.z.union([cF.extend({choices:G.z.array(G.z.object({message:G.z.object({role:G.z.literal("assistant"),content:G.z.string().nullable().optional(),reasoning:G.z.string().nullable().optional(),reasoning_details:ch.nullish(),images:cE.nullish(),tool_calls:G.z.array(G.z.object({id:G.z.string().optional().nullable(),type:G.z.literal("function"),function:G.z.object({name:G.z.string(),arguments:G.z.string().optional()}).passthrough()}).passthrough()).optional(),annotations:G.z.array(G.z.union([G.z.object({type:G.z.literal("url_citation"),url_citation:G.z.object({url:G.z.string(),title:G.z.string().optional(),start_index:G.z.number().optional(),end_index:G.z.number().optional(),content:G.z.string().optional()}).passthrough()}).passthrough(),G.z.object({type:G.z.literal("file_annotation"),file_annotation:G.z.object({file_id:G.z.string(),quote:G.z.string().optional()}).passthrough()}).passthrough(),G.z.object({type:G.z.literal("file"),file:G.z.object({hash:G.z.string(),name:G.z.string(),content:G.z.array(G.z.object({type:G.z.string(),text:G.z.string().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough(),index:G.z.number().nullish(),logprobs:G.z.object({content:G.z.array(G.z.object({token:G.z.string(),logprob:G.z.number(),top_logprobs:G.z.array(G.z.object({token:G.z.string(),logprob:G.z.number()}).passthrough())}).passthrough()).nullable()}).passthrough().nullable().optional(),finish_reason:G.z.string().optional().nullable()}).passthrough())}),ci.extend({user_id:G.z.string().optional()})]),cH=G.z.union([cF.extend({choices:G.z.array(G.z.object({delta:G.z.object({role:G.z.enum(["assistant"]).optional(),content:G.z.string().nullish(),reasoning:G.z.string().nullish().optional(),reasoning_details:ch.nullish(),images:cE.nullish(),tool_calls:G.z.array(G.z.object({index:G.z.number().nullish(),id:G.z.string().nullish(),type:G.z.literal("function").optional(),function:G.z.object({name:G.z.string().nullish(),arguments:G.z.string().nullish()}).passthrough()}).passthrough()).nullish(),annotations:G.z.array(G.z.union([G.z.object({type:G.z.literal("url_citation"),url_citation:G.z.object({url:G.z.string(),title:G.z.string().optional(),start_index:G.z.number().optional(),end_index:G.z.number().optional(),content:G.z.string().optional()}).passthrough()}).passthrough(),G.z.object({type:G.z.literal("file_annotation"),file_annotation:G.z.object({file_id:G.z.string(),quote:G.z.string().optional()}).passthrough()}).passthrough(),G.z.object({type:G.z.literal("file"),file:G.z.object({hash:G.z.string(),name:G.z.string(),content:G.z.array(G.z.object({type:G.z.string(),text:G.z.string().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough().nullish(),logprobs:G.z.object({content:G.z.array(G.z.object({token:G.z.string(),logprob:G.z.number(),top_logprobs:G.z.array(G.z.object({token:G.z.string(),logprob:G.z.number()}).passthrough())}).passthrough()).nullable()}).passthrough().nullish(),finish_reason:G.z.string().nullable().optional(),index:G.z.number().nullish()}).passthrough())}),ci]),cI=class{constructor(a,b,c){this.specificationVersion="v4",this.provider="openrouter",this.defaultObjectGenerationMode="tool",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)(?:[?#].*)?$/i],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.modelId=a,this.settings=b,this.config=c}getArgs({prompt:a,maxOutputTokens:b,temperature:c,topP:d,frequencyPenalty:e,presencePenalty:f,seed:g,stopSequences:h,responseFormat:i,topK:j,tools:k,toolChoice:l}){var m,n,o,p;let q=P(P({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:!0===this.settings.logprobs||"number"==typeof this.settings.logprobs||void 0,top_logprobs:"number"==typeof this.settings.logprobs?this.settings.logprobs:"boolean"==typeof this.settings.logprobs&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:null!=b?b:this.settings.maxTokens,temperature:null!=c?c:this.settings.temperature,top_p:null!=d?d:this.settings.topP,frequency_penalty:null!=e?e:this.settings.frequencyPenalty,presence_penalty:null!=f?f:this.settings.presencePenalty,seed:g,stop:h,response_format:(null==i?void 0:i.type)==="json"?null!=i.schema?{type:"json_schema",json_schema:P({schema:i.schema,strict:null==(n=null==(m=this.settings.structuredOutputs)?void 0:m.strict)||n,name:null!=(o=i.name)?o:"response"},i.description&&{description:i.description})}:{type:"json_object"}:void 0,top_k:null!=j?j:this.settings.topK,messages:function(a){var b,c,d,e,f,g,h,i;let j=[],k=new cs;for(let{role:l,content:m,providerOptions:n}of a)switch(l){case"system":{let a=cB(n);j.push({role:"system",content:[P({type:"text",text:m},a&&{cache_control:a})]});break}case"user":{if(1===m.length&&(null==(b=m[0])?void 0:b.type)==="text"){let a=null!=(c=cB(n))?c:cB(m[0].providerOptions),b=a?[{type:"text",text:m[0].text,cache_control:a}]:m[0].text;j.push({role:"user",content:b});break}let a=cB(n),e=-1;for(let a=m.length-1;a>=0;a--)if((null==(d=m[a])?void 0:d.type)==="text"){e=a;break}let f=m.map((b,c)=>{var d,f,g,h,i,j,k;let l="text"===b.type&&c===e,m=cB(b.providerOptions),n="text"===b.type?null!=m?m:l?a:void 0:m;switch(b.type){case"text":return P({type:"text",text:b.text},n&&{cache_control:n});case"file":{if(null==(d=b.mediaType)?void 0:d.startsWith("image/"))return P({type:"image_url",image_url:{url:cw({part:b,defaultMediaType:"image/jpeg"})}},n&&{cache_control:n});if(null==(f=b.mediaType)?void 0:f.startsWith("video/"))return P({type:"video_url",video_url:{url:cw({part:b,defaultMediaType:"video/mp4"})}},n&&{cache_control:n});if(null==(g=b.mediaType)?void 0:g.startsWith("audio/"))return P({type:"input_audio",input_audio:function(a){let b=cw({part:a,defaultMediaType:"audio/mpeg"});if(cu({url:b,protocols:new Set(["http:","https:"])}))throw Error(`Audio files cannot be provided as URLs.
|
|
228
|
+
|
|
229
|
+
OpenRouter requires audio to be base64-encoded. Please:
|
|
230
|
+
1. Download the audio file locally
|
|
231
|
+
2. Read it as a Buffer or Uint8Array
|
|
232
|
+
3. Pass it as the data parameter
|
|
233
|
+
|
|
234
|
+
The AI SDK will automatically handle base64 encoding.
|
|
235
|
+
|
|
236
|
+
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);let c=cz(b),d=a.mediaType||"audio/mpeg",e=cA[d.replace("audio/","")];if(void 0===e){let a=ct.join(", ");throw Error(`Unsupported audio format: "${d}"
|
|
237
|
+
|
|
238
|
+
OpenRouter supports the following audio formats: ${a}
|
|
239
|
+
|
|
240
|
+
Learn more: https://openrouter.ai/docs/features/multimodal/audio`)}return{data:c,format:e}}(b)},n&&{cache_control:n});let a=String(null!=(k=null!=(j=null==(i=null==(h=b.providerOptions)?void 0:h.openrouter)?void 0:i.filename)?j:b.filename)?k:""),c=cw({part:b,defaultMediaType:"application/pdf"});if(cu({url:c,protocols:new Set(["http:","https:"])}))return{type:"file",file:{filename:a,file_data:c}};return P({type:"file",file:{filename:a,file_data:c}},n&&{cache_control:n})}default:return P({type:"text",text:""},n&&{cache_control:n})}});j.push({role:"user",content:f});break}case"assistant":{let a,b="",c="",d=[];for(let a of m)switch(a.type){case"text":b+=a.text;break;case"tool-call":d.push({id:a.toolCallId,type:"function",function:{name:a.toolName,arguments:JSON.stringify(function a(b){if(null==b)return b;if(Array.isArray(b))return b.map(a);if("object"==typeof b){let c={},d=Object.entries(b);for(let[b,e]of(d.sort(([a],[b])=>a.localeCompare(b)),d))c[b]=a(e);return c}return b}(a.input))}});break;case"reasoning":c+=a.text}let i=cm.safeParse(n),l=i.success?null==(f=null==(e=i.data)?void 0:e.openrouter)?void 0:f.reasoning_details:void 0,o=i.success?null==(h=null==(g=i.data)?void 0:g.openrouter)?void 0:h.annotations:void 0,p=l&&Array.isArray(l)?l:function(a){var b,c,d,e;for(let d of a)if("tool-call"===d.type){let a=cm.safeParse(d.providerOptions);if(a.success&&(null==(c=null==(b=a.data)?void 0:b.openrouter)?void 0:c.reasoning_details)&&a.data.openrouter.reasoning_details.length>0)return a.data.openrouter.reasoning_details}for(let b of a)if("reasoning"===b.type){let a=cm.safeParse(b.providerOptions);if(a.success&&(null==(e=null==(d=a.data)?void 0:d.openrouter)?void 0:e.reasoning_details)&&a.data.openrouter.reasoning_details.length>0)return a.data.openrouter.reasoning_details}}(m);if(p){let b=p.filter(a=>{var b;if("reasoning.text"!==a.type)return!0;let c=null!=(b=a.format)?b:"anthropic-claude-v1";return"anthropic-claude-v1"!==c&&"google-gemini-v1"!==c||!!a.signature});if(b.length<p.length){let a=globalThis.AI_SDK_LOG_WARNINGS;!1!==a&&"function"!=typeof a&&console.warn("[openrouter] Some reasoning_details entries were removed because they were missing signatures. See https://github.com/OpenRouterTeam/ai-sdk-provider/issues/423 and https://github.com/OpenRouterTeam/ai-sdk-provider/issues/418 for more details.")}let c=[];for(let a of b)k.upsert(a)&&c.push(a);a=c}let q=c&&a&&a.length>0?c:void 0;j.push({role:"assistant",content:b||null,tool_calls:d.length>0?d:void 0,reasoning:q,reasoning_details:a,annotations:o,cache_control:cB(n)});break}case"tool":for(let a of m){if("tool-approval-response"===a.type)continue;let b=function(a){var b;switch(a.output.type){case"text":case"error-text":return a.output.value;case"json":case"error-json":return JSON.stringify(a.output.value);case"content":return a.output.value.map(a=>{var b,c,d,e;switch(a.type){case"text":return{type:"text",text:a.text};case"file":{let f=cx({data:a.data,mediaType:a.mediaType,defaultMediaType:"application/octet-stream"});if(null==(b=a.mediaType)?void 0:b.startsWith("image/"))return{type:"image_url",image_url:{url:f}};if(null==(c=a.mediaType)?void 0:c.startsWith("video/"))return{type:"video_url",video_url:{url:f}};if(null==(d=a.mediaType)?void 0:d.startsWith("audio/")){let b=cA[a.mediaType.replace("audio/","")];if(void 0!==b)return{type:"input_audio",input_audio:{data:cz(f),format:b}}}return{type:"file",file:{filename:null!=(e=a.filename)?e:"",file_data:f}}}default:return{type:"text",text:JSON.stringify(a)}}});case"execution-denied":return null!=(b=a.output.reason)?b:"Tool execution denied"}}(a);j.push({role:"tool",tool_call_id:a.toolCallId,content:b,name:a.toolName,cache_control:null!=(i=cB(n))?i:cB(a.providerOptions)})}}return j}(a),include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning,usage:this.settings.usage,plugins:this.settings.plugins,web_search_options:this.settings.web_search_options,provider:this.settings.provider,debug:this.settings.debug,cache_control:this.settings.cache_control},this.config.extraBody),this.settings.extraBody);if(k&&k.length>0){let a=[];for(let b of k)if("function"===b.type){let c=null==(p=b.providerOptions)?void 0:p.openrouter,d=null==c?void 0:c.eager_input_streaming;a.push(P({type:"function",function:{name:b.name,description:b.description,parameters:b.inputSchema}},null!=d&&{eager_input_streaming:d}))}else"provider"===b.type&&a.push(function(a){let[b,c]=a.id.split("."),d=`${b}:${c}`,e={};for(let[b,c]of Object.entries(a.args))void 0!==c&&(e[b.replace(/[A-Z]/g,a=>`_${a.toLowerCase()}`)]=c);return P({type:d},e)}(b));return Q(P({},q),{tools:a,tool_choice:l?function(a){switch(a.type){case"auto":case"none":case"required":return a.type;case"tool":return{type:"function",function:{name:a.toolName}};default:throw new ah({argument:"toolChoice",message:`Invalid tool choice type: ${JSON.stringify(a)}`})}}(l):void 0})}return q}async doGenerate(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v;let w=(a.providerOptions||{}).openrouter||{},{cacheControl:x}=w,y=R(w,["cacheControl"]),z=P(P(P({},this.getArgs(a)),y),null==x||"cache_control"in y?{}:{cache_control:x}),{value:A,responseHeaders:B}=await b1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:aU(this.config.headers(),a.headers),body:z,failedResponseHandler:cj,successfulResponseHandler:b6(cG),abortSignal:a.abortSignal,fetch:this.config.fetch});if("error"in A){let a=A.error;throw new Z({message:a.message,url:this.config.url({path:"/chat/completions",modelId:this.modelId}),requestBodyValues:z,statusCode:200,responseHeaders:B,data:a})}let C=A.choices[0];if(!C)throw new aF({message:"No choice in response"});let D=A.usage?cn(A.usage):co(),E=null!=(b=C.message.reasoning_details)?b:[],F=E.length>0?E.map(a=>{switch(a.type){case"reasoning.text":if(a.text)return{type:"reasoning",text:a.text,providerMetadata:{openrouter:{reasoning_details:[a]}}};break;case"reasoning.summary":if(a.summary)return{type:"reasoning",text:a.summary,providerMetadata:{openrouter:{reasoning_details:[a]}}}}return null}).filter(a=>null!==a):C.message.reasoning?[{type:"reasoning",text:C.message.reasoning}]:[],G=[];if(G.push(...F),C.message.content&&G.push({type:"text",text:C.message.content}),C.message.tool_calls){let a=!1,b=new Set;for(let d of C.message.tool_calls){let e=d.id;(!e||b.has(e))&&(e=bm()),b.add(e),G.push({type:"tool-call",toolCallId:e,toolName:d.function.name,input:null!=(c=d.function.arguments)?c:"{}",providerMetadata:a?void 0:{openrouter:{reasoning_details:E}}}),a=!0}}if(C.message.images)for(let a of C.message.images)G.push({type:"file",mediaType:cy(a.image_url.url,"image/jpeg"),data:{type:"data",data:cz(a.image_url.url)}});if(C.message.annotations)for(let a of C.message.annotations)"url_citation"===a.type&&G.push({type:"source",sourceType:"url",id:a.url_citation.url,url:a.url_citation.url,title:null!=(d=a.url_citation.title)?d:"",providerMetadata:{openrouter:{content:null!=(e=a.url_citation.content)?e:"",startIndex:null!=(f=a.url_citation.start_index)?f:0,endIndex:null!=(g=a.url_citation.end_index)?g:0}}});let H=null==(h=C.message.annotations)?void 0:h.filter(a=>"file"===a.type),I=C.message.tool_calls&&C.message.tool_calls.length>0,J=E.some(a=>"reasoning.encrypted"===a.type&&a.data),K=I&&J&&"stop"===C.finish_reason?cq("tool-calls",null!=(i=C.finish_reason)?i:void 0):cp(C.finish_reason);return{content:G,finishReason:I&&"other"===K.unified?cq("tool-calls",K.raw):K,usage:D,warnings:[],providerMetadata:{openrouter:cl.parse({provider:null!=(j=A.provider)?j:"",reasoning_details:null!=(k=C.message.reasoning_details)?k:[],annotations:H&&H.length>0?H:void 0,usage:P(P(P(P({promptTokens:null!=(l=D.inputTokens.total)?l:0,completionTokens:null!=(m=D.outputTokens.total)?m:0,totalTokens:(null!=(n=D.inputTokens.total)?n:0)+(null!=(o=D.outputTokens.total)?o:0)},(null==(p=A.usage)?void 0:p.cost)!=null?{cost:A.usage.cost}:{}),(null==(r=null==(q=A.usage)?void 0:q.prompt_tokens_details)?void 0:r.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:A.usage.prompt_tokens_details.cached_tokens}}:{}),(null==(t=null==(s=A.usage)?void 0:s.completion_tokens_details)?void 0:t.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:A.usage.completion_tokens_details.reasoning_tokens}}:{}),(null==(v=null==(u=A.usage)?void 0:u.cost_details)?void 0:v.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:A.usage.cost_details.upstream_inference_cost}}:{})})},request:{body:z},response:{id:A.id,modelId:A.model,headers:B,body:A}}}async doStream(a){var b;let c,d,e,f,g,h,i=(a.providerOptions||{}).openrouter||{},{cacheControl:j}=i,k=R(i,["cacheControl"]),l=P(P(P({},this.getArgs(a)),k),null==j||"cache_control"in k?{}:{cache_control:j}),{value:m,responseHeaders:n}=await b1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:aU(this.config.headers(),a.headers),body:Q(P({},l),{stream:!0,stream_options:"strict"===this.config.compatibility?P({include_usage:!0},(null==(b=this.settings.usage)?void 0:b.include)?{include_usage:!0}:{}):void 0}),failedResponseHandler:cj,successfulResponseHandler:b5(cH),abortSignal:a.abortSignal,fetch:this.config.fetch}),o=cr(m,a=>{c=a}),p=[],q=new Set,r=cq("other"),s={inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0},t={},u=[],v=!1,w=[],x=!1,y=!1,z=[];return{stream:o.pipeThrough(new TransformStream({start(a){a.enqueue({type:"stream-start",warnings:z})},transform(b,c){var i,j,k,l,m,n,o,z,A,B,C,D,E,F,G,H,I,J,K,L,M;if(a.includeRawChunks&&c.enqueue({type:"raw",rawValue:b.rawValue}),!b.success){r=cq("error"),c.enqueue({type:"error",error:b.error});return}let N=b.value;if("error"in N){r=cq("error"),c.enqueue({type:"error",error:N.error});return}if(N.provider&&(h=N.provider),N.id&&(g=N.id,c.enqueue({type:"response-metadata",id:N.id})),N.model&&c.enqueue({type:"response-metadata",modelId:N.model}),null!=N.usage){let a=cn(N.usage);Object.assign(s.inputTokens,a.inputTokens),Object.assign(s.outputTokens,a.outputTokens),d=N.usage;let b=null!=(i=N.usage.prompt_tokens)?i:0,c=null!=(j=N.usage.completion_tokens)?j:0;t.promptTokens=b,N.usage.prompt_tokens_details&&(t.promptTokensDetails={cachedTokens:null!=(k=N.usage.prompt_tokens_details.cached_tokens)?k:0}),t.completionTokens=c,N.usage.completion_tokens_details&&(t.completionTokensDetails={reasoningTokens:null!=(l=N.usage.completion_tokens_details.reasoning_tokens)?l:0}),null!=N.usage.cost&&(t.cost=N.usage.cost),t.totalTokens=N.usage.total_tokens;let e=null==(m=N.usage.cost_details)?void 0:m.upstream_inference_cost;null!=e&&(t.costDetails={upstreamInferenceCost:e})}let O=N.choices[0];if((null==O?void 0:O.finish_reason)!=null&&(r=cp(O.finish_reason)),(null==O?void 0:O.delta)==null)return;let Q=O.delta,R=a=>{y||(f=bm(),c.enqueue({type:"reasoning-start",id:f}),y=!0),c.enqueue({type:"reasoning-delta",delta:a,id:f||bm()})};if(Q.reasoning_details&&Q.reasoning_details.length>0){for(let a of Q.reasoning_details){let b=u[u.length-1];"reasoning.text"===a.type?(null==b?void 0:b.type)==="reasoning.text"?(b.text=(b.text||"")+(a.text||""),b.signature=b.signature||a.signature,b.format=b.format||a.format):u.push(P({},a)):"reasoning.summary"===a.type?(null==b?void 0:b.type)==="reasoning.summary"?(b.summary=(b.summary||"")+(a.summary||""),b.format=b.format||a.format):u.push(P({},a)):u.push(a)}if(!x)for(let a of Q.reasoning_details)switch(a.type){case"reasoning.text":R(a.text||"");break;case"reasoning.encrypted":break;case"reasoning.summary":a.summary&&R(a.summary)}}else Q.reasoning&&!x&&R(Q.reasoning);if(Q.content&&(y&&!x&&(c.enqueue({type:"reasoning-end",id:f||bm(),providerMetadata:{openrouter:{reasoning_details:u}}}),y=!1),x||(e=g||bm(),c.enqueue({type:"text-start",id:e}),x=!0),c.enqueue({type:"text-delta",delta:Q.content,id:e||bm()})),Q.annotations){for(let a of Q.annotations)if("url_citation"===a.type)c.enqueue({type:"source",sourceType:"url",id:a.url_citation.url,url:a.url_citation.url,title:null!=(n=a.url_citation.title)?n:"",providerMetadata:{openrouter:{content:null!=(o=a.url_citation.content)?o:"",startIndex:null!=(z=a.url_citation.start_index)?z:0,endIndex:null!=(A=a.url_citation.end_index)?A:0}}});else if("file"===a.type){let b=a.file;b&&"object"==typeof b&&"hash"in b&&"name"in b&&w.push(a)}}if(null!=Q.tool_calls)for(let a of Q.tool_calls){let b=null!=(B=a.index)?B:p.length-1;if(null==p[b]){if("function"!==a.type)throw new ap({data:a,message:"Expected 'function' type."});if((null==(C=a.function)?void 0:C.name)==null)throw new ap({data:a,message:"Expected 'function.name' to be a string."});let d=null!=(D=a.id)?D:"";(!d||q.has(d))&&(d=bm()),q.add(d),p[b]={id:d,type:"function",function:{name:a.function.name,arguments:null!=(E=a.function.arguments)?E:""},inputStarted:!1,sent:!1};let e=p[b];if(null==e)throw new ap({data:{index:b,toolCallsLength:p.length},message:`Tool call at index ${b} is missing after creation.`});(null==(F=e.function)?void 0:F.name)!=null&&(null==(G=e.function)?void 0:G.arguments)!=null&&b$(e.function.arguments)&&(e.inputStarted=!0,c.enqueue({type:"tool-input-start",id:e.id,toolName:e.function.name}),c.enqueue({type:"tool-input-delta",id:e.id,delta:e.function.arguments}),c.enqueue({type:"tool-input-end",id:e.id}),c.enqueue({type:"tool-call",toolCallId:e.id,toolName:e.function.name,input:e.function.arguments,providerMetadata:v?void 0:{openrouter:{reasoning_details:u}}}),v=!0,e.sent=!0);continue}let d=p[b];if(null==d)throw new ap({data:{index:b,toolCallsLength:p.length,toolCallDelta:a},message:`Tool call at index ${b} is missing during merge.`});!d.inputStarted&&(d.inputStarted=!0,c.enqueue({type:"tool-input-start",id:d.id,toolName:d.function.name}),d.function.arguments&&c.enqueue({type:"tool-input-delta",id:d.id,delta:d.function.arguments})),(null==(H=a.function)?void 0:H.arguments)!=null&&(d.function.arguments+=null!=(J=null==(I=a.function)?void 0:I.arguments)?J:""),c.enqueue({type:"tool-input-delta",id:d.id,delta:null!=(K=a.function.arguments)?K:""}),!d.sent&&(null==(L=d.function)?void 0:L.name)!=null&&(null==(M=d.function)?void 0:M.arguments)!=null&&b$(d.function.arguments)&&(c.enqueue({type:"tool-input-end",id:d.id}),c.enqueue({type:"tool-call",toolCallId:d.id,toolName:d.function.name,input:d.function.arguments,providerMetadata:v?void 0:{openrouter:{reasoning_details:u}}}),v=!0,d.sent=!0)}if(null!=Q.images)for(let a of Q.images)c.enqueue({type:"file",mediaType:cy(a.image_url.url,"image/jpeg"),data:{type:"data",data:cz(a.image_url.url)}})},flush(a){let b=p.length>0;null!=c&&(r=cq("error"),a.enqueue({type:"error",error:c}));let g=u.some(a=>"reasoning.encrypted"===a.type&&a.data);if(b&&g&&"stop"===r.unified&&(r=cq("tool-calls",r.raw)),b&&"other"===r.unified&&(r=cq("tool-calls",r.raw)),"tool-calls"===r.unified){for(let b of p)if(b&&!b.sent){let c=b$(b.function.arguments)?b.function.arguments:"{}";b.inputStarted||(a.enqueue({type:"tool-input-start",id:b.id,toolName:b.function.name}),a.enqueue({type:"tool-input-delta",id:b.id,delta:c})),a.enqueue({type:"tool-input-end",id:b.id}),a.enqueue({type:"tool-call",toolCallId:b.id,toolName:b.function.name,input:c,providerMetadata:v?void 0:{openrouter:{reasoning_details:u}}}),v=!0,b.sent=!0}}y&&a.enqueue({type:"reasoning-end",id:f||bm(),providerMetadata:{openrouter:{reasoning_details:u}}}),x&&a.enqueue({type:"text-end",id:e||bm()});let i={usage:t};void 0!==h&&(i.provider=h),i.reasoning_details=u,w.length>0&&(i.annotations=w),void 0===s.inputTokens.total&&void 0!==t.promptTokens&&(s.inputTokens.total=t.promptTokens),void 0===s.outputTokens.total&&void 0!==t.completionTokens&&(s.outputTokens.total=t.completionTokens),s.raw=d,a.enqueue({type:"finish",finishReason:r,usage:s,providerMetadata:{openrouter:i}})}})),warnings:z,request:{body:l},response:{headers:n}}}},cJ=G.z.union([G.z.object({id:G.z.string().optional(),model:G.z.string().optional(),provider:G.z.string().optional(),choices:G.z.array(G.z.object({text:G.z.string(),reasoning:G.z.string().nullish().optional(),reasoning_details:ch.nullish(),finish_reason:G.z.string().nullish(),index:G.z.number().nullish(),logprobs:G.z.object({tokens:G.z.array(G.z.string()),token_logprobs:G.z.array(G.z.number()),top_logprobs:G.z.array(G.z.record(G.z.string(),G.z.number())).nullable()}).passthrough().nullable().optional()}).passthrough()),usage:G.z.object({prompt_tokens:G.z.number(),prompt_tokens_details:G.z.object({cached_tokens:G.z.number(),cache_write_tokens:G.z.number().nullish()}).passthrough().nullish(),completion_tokens:G.z.number(),completion_tokens_details:G.z.object({reasoning_tokens:G.z.number()}).passthrough().nullish(),total_tokens:G.z.number(),cost:G.z.number().optional(),cost_details:G.z.object({upstream_inference_cost:G.z.number().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),ci]),cK=class{constructor(a,b,c){this.specificationVersion="v4",this.provider="openrouter",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)(?:[?#].*)?$/i],"text/*":[/^data:text\//,/^https?:\/\/.+$/],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.defaultObjectGenerationMode=void 0,this.modelId=a,this.settings=b,this.config=c}getArgs({prompt:a,maxOutputTokens:b,temperature:c,topP:d,frequencyPenalty:e,presencePenalty:f,seed:g,responseFormat:h,topK:i,stopSequences:j,tools:k,toolChoice:l}){let{prompt:m}=function({prompt:a,inputFormat:b,user:c="user",assistant:d="assistant"}){if("prompt"===b&&1===a.length&&a[0]&&"user"===a[0].role&&1===a[0].content.length&&a[0].content[0]&&"text"===a[0].content[0].type)return{prompt:a[0].content[0].text};let e="";for(let{role:b,content:f}of(a[0]&&"system"===a[0].role&&(e+=`${a[0].content}
|
|
241
|
+
|
|
242
|
+
`,a=a.slice(1)),a))switch(b){case"system":throw new al({message:`Unexpected system message in prompt: ${f}`,prompt:a});case"user":{let a=f.map(a=>{switch(a.type){case"text":return a.text;case"file":throw new aO({functionality:"file attachments"});default:return""}}).join("");e+=`${c}:
|
|
243
|
+
${a}
|
|
244
|
+
|
|
245
|
+
`;break}case"assistant":{let a=f.map(a=>{switch(a.type){case"text":return a.text;case"tool-call":throw new aO({functionality:"tool-call messages"});case"tool-result":throw new aO({functionality:"tool-result messages"});case"reasoning":throw new aO({functionality:"reasoning messages"});case"file":throw new aO({functionality:"file attachments"});default:return""}}).join("");e+=`${d}:
|
|
246
|
+
${a}
|
|
247
|
+
|
|
248
|
+
`;break}case"tool":throw new aO({functionality:"tool messages"})}return{prompt:e+=`${d}:
|
|
249
|
+
`}}({prompt:a,inputFormat:"prompt"});if(null==k?void 0:k.length)throw new aO({functionality:"tools"});if(l)throw new aO({functionality:"toolChoice"});return P(P({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:"number"==typeof this.settings.logprobs?this.settings.logprobs:"boolean"==typeof this.settings.logprobs&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:null!=b?b:this.settings.maxTokens,temperature:null!=c?c:this.settings.temperature,top_p:null!=d?d:this.settings.topP,frequency_penalty:null!=e?e:this.settings.frequencyPenalty,presence_penalty:null!=f?f:this.settings.presencePenalty,seed:g,stop:j,response_format:h,top_k:null!=i?i:this.settings.topK,prompt:m,include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning},this.config.extraBody),this.settings.extraBody)}async doGenerate(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;let s=(a.providerOptions||{}).openrouter||{},t=P(P({},this.getArgs(a)),s),{value:u,responseHeaders:v}=await b1({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:aU(this.config.headers(),a.headers),body:t,failedResponseHandler:cj,successfulResponseHandler:b6(cJ),abortSignal:a.abortSignal,fetch:this.config.fetch});if("error"in u){let a=u.error;throw new Z({message:a.message,url:this.config.url({path:"/completions",modelId:this.modelId}),requestBodyValues:t,statusCode:200,responseHeaders:v,data:a})}let w=u.choices[0];if(!w)throw new aF({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:null!=(b=w.text)?b:""}],finishReason:cp(w.finish_reason),usage:u.usage?cn(u.usage):co(),warnings:[],providerMetadata:{openrouter:cl.parse({provider:null!=(c=u.provider)?c:"",usage:P(P(P(P({promptTokens:null!=(e=null==(d=u.usage)?void 0:d.prompt_tokens)?e:0,completionTokens:null!=(g=null==(f=u.usage)?void 0:f.completion_tokens)?g:0,totalTokens:(null!=(i=null==(h=u.usage)?void 0:h.prompt_tokens)?i:0)+(null!=(k=null==(j=u.usage)?void 0:j.completion_tokens)?k:0)},(null==(l=u.usage)?void 0:l.cost)!=null?{cost:u.usage.cost}:{}),(null==(n=null==(m=u.usage)?void 0:m.prompt_tokens_details)?void 0:n.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:u.usage.prompt_tokens_details.cached_tokens}}:{}),(null==(p=null==(o=u.usage)?void 0:o.completion_tokens_details)?void 0:p.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:u.usage.completion_tokens_details.reasoning_tokens}}:{}),(null==(r=null==(q=u.usage)?void 0:q.cost_details)?void 0:r.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:u.usage.cost_details.upstream_inference_cost}}:{})})},response:{headers:v}}}async doStream(a){let b,c,d,e=(a.providerOptions||{}).openrouter||{},f=P(P({},this.getArgs(a)),e),{value:g,responseHeaders:h}=await b1({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:aU(this.config.headers(),a.headers),body:Q(P({},f),{stream:!0,stream_options:"strict"===this.config.compatibility?{include_usage:!0}:void 0}),failedResponseHandler:cj,successfulResponseHandler:b5(cJ),abortSignal:a.abortSignal,fetch:this.config.fetch}),i=cr(g,a=>{b=a}),j=cq("other"),k={inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0},l={},m=[];return{stream:i.pipeThrough(new TransformStream({start(a){a.enqueue({type:"stream-start",warnings:m})},transform(b,e){var f,g,h,i,m;if(a.includeRawChunks&&e.enqueue({type:"raw",rawValue:b.rawValue}),!b.success){j=cq("error"),e.enqueue({type:"error",error:b.error});return}let n=b.value;if("error"in n){j=cq("error"),e.enqueue({type:"error",error:n.error});return}if(n.provider&&(c=n.provider),null!=n.usage){let a=cn(n.usage);Object.assign(k.inputTokens,a.inputTokens),Object.assign(k.outputTokens,a.outputTokens),d=n.usage;let b=null!=(f=n.usage.prompt_tokens)?f:0,c=null!=(g=n.usage.completion_tokens)?g:0;l.promptTokens=b,n.usage.prompt_tokens_details&&(l.promptTokensDetails={cachedTokens:null!=(h=n.usage.prompt_tokens_details.cached_tokens)?h:0}),l.completionTokens=c,n.usage.completion_tokens_details&&(l.completionTokensDetails={reasoningTokens:null!=(i=n.usage.completion_tokens_details.reasoning_tokens)?i:0}),null!=n.usage.cost&&(l.cost=n.usage.cost),l.totalTokens=n.usage.total_tokens;let e=null==(m=n.usage.cost_details)?void 0:m.upstream_inference_cost;null!=e&&(l.costDetails={upstreamInferenceCost:e})}let o=n.choices[0];(null==o?void 0:o.finish_reason)!=null&&(j=cp(o.finish_reason)),(null==o?void 0:o.text)!=null&&e.enqueue({type:"text-delta",delta:o.text,id:bm()})},flush(a){null!=b&&(j=cq("error"),a.enqueue({type:"error",error:b})),k.raw=d;let e={usage:l};void 0!==c&&(e.provider=c),a.enqueue({type:"finish",finishReason:j,usage:k,providerMetadata:{openrouter:e}})}})),response:{headers:h}}}},cL=G.z.object({prompt_tokens:G.z.number(),total_tokens:G.z.number(),cost:G.z.number().optional()}),cM=G.z.object({object:G.z.literal("embedding"),embedding:G.z.array(G.z.number()),index:G.z.number().optional()}),cN=G.z.object({id:G.z.string().optional(),object:G.z.literal("list"),data:G.z.array(cM),model:G.z.string(),provider:G.z.string().optional(),usage:cL.optional()}),cO=class{constructor(a,b,c){this.specificationVersion="v4",this.provider="openrouter",this.maxEmbeddingsPerCall=void 0,this.supportsParallelCalls=!0,this.modelId=a,this.settings=b,this.config=c}async doEmbed(a){var b,c,d,e,f,g;let{values:h,abortSignal:i,headers:j}=a,k=P(P({model:this.modelId,input:h,user:this.settings.user,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody),{value:l,responseHeaders:m}=await b1({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:aU(this.config.headers(),j),body:k,failedResponseHandler:cj,successfulResponseHandler:b6(cN),abortSignal:i,fetch:this.config.fetch});return{embeddings:l.data.map(a=>a.embedding),usage:l.usage?{tokens:l.usage.prompt_tokens}:void 0,providerMetadata:{openrouter:cl.parse({provider:null!=(b=l.provider)?b:"",usage:P({promptTokens:null!=(d=null==(c=l.usage)?void 0:c.prompt_tokens)?d:0,completionTokens:0,totalTokens:null!=(f=null==(e=l.usage)?void 0:e.total_tokens)?f:0},(null==(g=l.usage)?void 0:g.cost)!=null?{cost:l.usage.cost}:{})})},response:{headers:m,body:l},warnings:[]}}},cP=G.z.lazy(()=>G.z.union([G.z.string(),G.z.number(),G.z.boolean(),G.z.null(),G.z.array(cP),G.z.record(G.z.string(),cP)])),cQ=G.z.union([G.z.string(),G.z.record(G.z.string(),cP),G.z.array(cP)]),cR=G.z.object({user:G.z.string().optional(),provider:G.z.record(G.z.string(),cP).optional(),session_id:G.z.string().optional(),trace:G.z.record(G.z.string(),cP).optional()}).loose(),cS=G.z.object({type:G.z.literal("noul"),noul:G.z.number()}),cT=G.z.object({type:G.z.literal("choice"),choice:G.z.string(),probabilities:G.z.record(G.z.string(),G.z.number()).optional(),confidence:G.z.number().optional()}),cU=G.z.object({type:G.z.literal("score"),score:G.z.number(),legend:G.z.record(G.z.string(),cQ).optional(),probabilities:G.z.record(G.z.string(),G.z.number()).optional(),confidence:G.z.number().optional()}),cV=G.z.discriminatedUnion("type",[cS,cT,cU]),cW=G.z.object({id:G.z.string().optional(),model:G.z.string().optional(),provider:G.z.string().optional(),answers:G.z.record(G.z.string(),cV),usage:G.z.object({input_tokens:G.z.number().optional(),output_tokens:G.z.number().optional(),cost:G.z.number().optional()}).optional()}),cX={probabilityDecimals:2,scoreDecimals:2},cY=class{constructor(a,b,c){this.specificationVersion="v4",this.provider="openrouter",this.supportedQuestionTypes=["choice","score","boolean"],this.modelId=a,this.settings=b,this.config=c}async doEvaluate(a){var b;let{state:c,questions:d,abortSignal:e,headers:f,providerOptions:g}=a,h=Object.fromEntries(Object.entries(d).map(([a,b])=>[a,function(a,b){var c,d;switch(b.type){case"choice":return{type:"choice",instructions:b.instructions,criteria:b.criteria};case"score":return{type:"score",instructions:b.instructions,criteria:b.criteria.map((b,c)=>{if(null==b)throw new ah({argument:`questions.${a}.criteria[${c}]`,message:`Question "${a}": the OpenRouter Decisions API requires a description for every score criterion.`});return b})};case"boolean":{let e=null==(c=b.criteria)?void 0:c.true,f=null==(d=b.criteria)?void 0:d.false;if(null==e&&null==f)return{type:"noul",instructions:b.instructions};if(null==e||null==f)throw new ah({argument:`questions.${a}.criteria`,message:`Question "${a}": the OpenRouter Decisions API requires both "true" and "false" descriptions when boolean criteria are given.`});return{type:"noul",instructions:b.instructions,criteria:{true:e,false:f}}}default:return b}}(a,b)])),i=await b_({provider:"openrouter",providerOptions:g,schema:cR}),{user:j,provider:k,session_id:l,trace:m,extraBody:n}=this.settings,o=Q(P(P(P(P({},this.config.extraBody),n),Object.fromEntries(Object.entries({user:j,provider:k,session_id:l,trace:m}).filter(([a,b])=>null!=b))),i),{model:this.modelId,state:c,questions:h}),{value:p,rawValue:q,responseHeaders:r}=await b1({url:this.config.url({path:"/decisions"}),headers:aU(this.config.headers(),f),body:o,failedResponseHandler:cj,successfulResponseHandler:b6(cW),abortSignal:e,fetch:this.config.fetch}),s=Object.fromEntries(Object.entries(p.answers).map(([a,b])=>[a,function(a){switch(a.type){case"noul":return{type:"boolean",probability:a.noul};case"choice":return{type:"choice",choice:a.choice,probabilities:a.probabilities};case"score":return{type:"score",score:a.score,probabilities:a.probabilities};default:return a}}(b)])),t=Object.fromEntries(Object.entries(p.answers).map(([a,b])=>[a,function(a){switch(a.type){case"noul":return{};case"choice":return null!=a.confidence?{confidence:a.confidence}:{};case"score":return P(P({},null!=a.confidence?{confidence:a.confidence}:{}),null!=a.legend?{legend:a.legend}:{});default:return a}}(b)]));return{answers:s,rounding:cX,usage:p.usage?{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens}:void 0,warnings:[],providerMetadata:{openrouter:P(Q(P({},null!=p.provider?{provider:p.provider}:{}),{answers:t}),(null==(b=p.usage)?void 0:b.cost)!=null?{usage:{cost:p.usage.cost}}:{})},response:{id:p.id,modelId:p.model,headers:r,body:q}}}},cZ=G.z.object({created:G.z.number().optional(),data:G.z.array(G.z.object({b64_json:G.z.string()}).passthrough()),usage:G.z.object({prompt_tokens:G.z.number(),completion_tokens:G.z.number(),total_tokens:G.z.number()}).passthrough().optional()}).passthrough(),c$=class{constructor(a,b,c){this.specificationVersion="v4",this.provider="openrouter",this.maxImagesPerCall=10,this.modelId=a,this.settings=b,this.config=c}async doGenerate(a){let{prompt:b,n:c,size:d,aspectRatio:e,seed:f,files:g,mask:h,abortSignal:i,headers:j,providerOptions:k}=a,l=(null==k?void 0:k.openrouter)||{};if(void 0!==h)throw new aO({functionality:"image inpainting (mask parameter)"});let m=void 0!==g&&g.length>0?g.map(a=>{var b;return"url"===(b=a).type?{type:"image_url",image_url:{url:b.url}}:{type:"image_url",image_url:{url:cv({data:b.data,mediaType:b.mediaType,defaultMediaType:"image/png"})}}}):void 0,n=P(P(P(P(P(P(P(P(P(P({model:this.modelId,prompt:null!=b?b:""},void 0!==c&&{n:c}),void 0!==d&&{size:d}),void 0!==e&&{aspect_ratio:e}),void 0!==f&&{seed:f}),void 0!==m&&{input_references:m}),void 0!==this.settings.user&&{user:this.settings.user}),void 0!==this.settings.provider&&{provider:this.settings.provider}),this.config.extraBody),this.settings.extraBody),l),{value:o,responseHeaders:p}=await b1({url:this.config.url({path:"/images",modelId:this.modelId}),headers:aU(this.config.headers(),j),body:n,failedResponseHandler:cj,successfulResponseHandler:b6(cZ),abortSignal:i,fetch:this.config.fetch});if(!o.data||0===o.data.length)throw new aF({message:"No images in response"});let q=o.data.map(a=>a.b64_json),r=o.usage?{inputTokens:o.usage.prompt_tokens,outputTokens:o.usage.completion_tokens,totalTokens:o.usage.total_tokens}:void 0;return{images:q,warnings:[],response:{timestamp:new Date,modelId:this.modelId,headers:p},usage:r}}},c_=function({id:a,inputSchema:b}){return c=>{var{execute:d,outputSchema:e,needsApproval:f,toModelOutput:g,onInputStart:h,onInputDelta:i,onInputAvailable:j}=c;return{type:"provider",isProviderExecuted:!1,id:a,args:R(c,["execute","outputSchema","needsApproval","toModelOutput","onInputStart","onInputDelta","onInputAvailable"]),inputSchema:b,outputSchema:e,execute:d,needsApproval:f,toModelOutput:g,onInputStart:h,onInputDelta:i,onInputAvailable:j}}}({id:"openrouter.web_search",inputSchema:G.z.object({results:G.z.array(G.z.unknown()).optional()})}),c0=G.z.object({id:G.z.string(),generation_id:G.z.string().optional(),polling_url:G.z.string(),status:G.z.string()}).passthrough(),c1=G.z.object({id:G.z.string(),generation_id:G.z.string().optional(),polling_url:G.z.string(),status:G.z.string(),unsigned_urls:G.z.array(G.z.string()).optional(),usage:G.z.object({cost:G.z.number().optional(),is_byok:G.z.boolean().optional()}).passthrough().optional(),error:G.z.string().optional()}).passthrough(),c2=class{constructor(a,b,c){this.specificationVersion="v4",this.provider="openrouter",this.maxVideosPerCall=1,this.modelId=a,this.settings=b,this.config=c}async doGenerate(a){var b,c,d,e,f,g;let{prompt:h,n:i,aspectRatio:j,resolution:k,duration:l,seed:m,image:n,abortSignal:o,headers:p,providerOptions:q}=a,r=[];i>1&&r.push({type:"unsupported",feature:"n > 1",details:`OpenRouter video generation returns 1 video per call. Requested ${i} videos.`});let s=P(P(P(P(P(P(P(P(P({model:this.modelId,prompt:null!=h?h:""},void 0!==j&&{aspect_ratio:j}),void 0!==k&&{size:k}),void 0!==l&&{duration:l}),void 0!==m&&{seed:m}),void 0!==this.settings.generateAudio&&{generate_audio:this.settings.generateAudio}),void 0!==n&&{frame_images:["url"===(g=n).type?{type:"image_url",image_url:{url:g.url},frame_type:"first_frame"}:{type:"image_url",image_url:{url:cv({data:g.data,mediaType:g.mediaType,defaultMediaType:"image/png"})},frame_type:"first_frame"}]}),this.config.extraBody),this.settings.extraBody),q.openrouter),t=aU(this.config.headers(),p),{value:u,responseHeaders:v}=await b1({url:this.config.url({path:"/videos",modelId:this.modelId}),headers:t,body:s,failedResponseHandler:cj,successfulResponseHandler:b6(c0),abortSignal:o,fetch:this.config.fetch}),w=null!=(b=this.settings.pollIntervalMs)?b:2e3,x=null!=(c=this.settings.maxPollTimeMs)?c:6e5,y=await this.pollUntilComplete({jobId:u.id,headers:t,abortSignal:o,pollIntervalMs:w,maxPollTimeMs:x}),z=[];if(y.unsigned_urls)for(let a of y.unsigned_urls)z.push({type:"url",url:a,mediaType:"video/mp4"});return{videos:z,warnings:r,providerMetadata:{openrouter:{generationId:null!=(d=y.generation_id)?d:null,cost:null!=(f=null==(e=y.usage)?void 0:e.cost)?f:null}},response:{timestamp:new Date,modelId:this.modelId,headers:v}}}async pollUntilComplete({jobId:a,headers:b,abortSignal:c,pollIntervalMs:d,maxPollTimeMs:e}){var f;let g=Date.now();for(;Date.now()-g<e;){null==c||c.throwIfAborted(),await aV(d),null==c||c.throwIfAborted();let{value:e}=await bn({url:this.config.url({path:`/videos/${a}`,modelId:this.modelId}),headers:b,failedResponseHandler:cj,successfulResponseHandler:b6(c1),abortSignal:c,fetch:this.config.fetch});if("completed"===e.status)return{generation_id:e.generation_id,unsigned_urls:e.unsigned_urls,usage:e.usage};if("failed"===e.status||"dead"===e.status||"cancelled"===e.status||"expired"===e.status)throw new Z({message:null!=(f=e.error)?f:`Video generation failed with status: ${e.status}`,url:this.config.url({path:`/videos/${a}`,modelId:this.modelId}),requestBodyValues:{},statusCode:500,isRetryable:!1})}throw new Z({message:`Video generation timed out after ${e}ms`,url:this.config.url({path:`/videos/${a}`,modelId:this.modelId}),requestBodyValues:{},statusCode:408,isRetryable:!0})}};function c3(a={}){var b,c,d,e;let f=null!=(c=b8(null!=(b=a.baseURL)?b:a.baseUrl))?c:"https://openrouter.ai/api/v1",g=null!=(d=b8(a.decisionsBaseURL))?d:f.endsWith("/v1")?`${f.slice(0,-3)}/alpha`:void 0,h=null!=(e=a.compatibility)?e:"compatible",i=()=>(function(a,...b){let c=Object.fromEntries(Object.entries(!a?{}:a instanceof Headers?Object.fromEntries(a.entries()):Array.isArray(a)?Object.fromEntries(a):a).filter(([,a])=>null!=a)),d=Object.keys(c).find(a=>"user-agent"===a.toLowerCase()),e=d?c[d]:void 0,f=(null==e?void 0:e.trim())?e:b.filter(Boolean).join(" ");return Q(P({},Object.fromEntries(Object.entries(c).filter(([a])=>"user-agent"!==a.toLowerCase()))),{"user-agent":f})})(P(P(P(P({Authorization:`Bearer ${function({apiKey:a,environmentVariableName:b,apiKeyParameterName:c="apiKey",description:d}){if("string"==typeof a)return a;if(null!=a)throw new ax({message:`${d} API key must be a string.`});if("u"<typeof process)throw new ax({message:`${d} API key is missing. Pass it using the '${c}' parameter. Environment variables are not supported in this environment.`});if(null==(a=process.env[b]))throw new ax({message:`${d} API key is missing. Pass it using the '${c}' parameter or the ${b} environment variable.`});if("string"!=typeof a)throw new ax({message:`${d} API key must be a string. The value of the ${b} environment variable is not a string.`});return a}({apiKey:a.apiKey,environmentVariableName:"OPENROUTER_API_KEY",description:"OpenRouter"})}`},a.appName&&{"X-OpenRouter-Title":a.appName}),a.appUrl&&{"HTTP-Referer":a.appUrl}),a.headers),a.api_keys&&Object.keys(a.api_keys).length>0&&{"X-Provider-API-Keys":JSON.stringify(a.api_keys)}),"ai-sdk/openrouter/3.1.0"),j=(b,c={})=>new cI(b,c,{provider:"openrouter.chat",url:({path:a})=>`${f}${a}`,headers:i,compatibility:h,fetch:a.fetch,extraBody:a.extraBody}),k=(b,c={})=>new cK(b,c,{provider:"openrouter.completion",url:({path:a})=>`${f}${a}`,headers:i,compatibility:h,fetch:a.fetch,extraBody:a.extraBody}),l=(b,c={})=>new cO(b,c,{provider:"openrouter.embedding",url:({path:a})=>`${f}${a}`,headers:i,fetch:a.fetch,extraBody:a.extraBody}),m=(a,b)=>{if(new.target)throw Error("The OpenRouter model function cannot be called with the new keyword.");return"openai/gpt-3.5-turbo-instruct"===a?k(a,b):j(a,b)},n=(a,b)=>m(a,b);return n.languageModel=m,n.chat=j,n.completion=k,n.textEmbeddingModel=l,n.embedding=l,n.imageModel=(b,c={})=>new c$(b,c,{provider:"openrouter.image",url:({path:a})=>`${f}${a}`,headers:i,fetch:a.fetch,extraBody:a.extraBody}),n.videoModel=(b,c={})=>new c2(b,c,{provider:"openrouter.video",url:({path:a})=>`${f}${a}`,headers:i,fetch:a.fetch,extraBody:a.extraBody}),n.evaluationModel=(b,c={})=>{if(null==g)throw new aB({message:`Cannot derive the Decisions API URL from baseURL "${f}" because it does not end in "/v1". Set \`decisionsBaseURL\` in createOpenRouter() to use evaluationModel().`});return new cY(b,c,{url:({path:a})=>`${g}${a}`,headers:i,fetch:a.fetch,extraBody:a.extraBody})},n.tools={webSearch:c_},n}c3({compatibility:"strict"}),a.s(["createOpenRouter",0,c3])},236338,(a,b,c)=>{"use strict";var d=Object.defineProperty,e=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,g=Object.prototype.hasOwnProperty,h={},i={SYMBOL_FOR_REQ_CONTEXT:()=>k,getContext:()=>l};for(var j in i)d(h,j,{get:i[j],enumerable:!0});b.exports=((a,b,c)=>{if(b&&"object"==typeof b||"function"==typeof b)for(let h of f(b))g.call(a,h)||void 0===h||d(a,h,{get:()=>b[h],enumerable:!(c=e(b,h))||c.enumerable});return a})(d({},"__esModule",{value:!0}),h);let k=Symbol.for("@vercel/request-context");function l(){let a=globalThis;return a[k]?.get?.()??{}}},817547,(a,b,c)=>{"use strict";var d=Object.defineProperty,e=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,g=Object.prototype.hasOwnProperty,h={},i={getVercelOidcToken:()=>m,getVercelOidcTokenSync:()=>n};for(var j in i)d(h,j,{get:i[j],enumerable:!0});b.exports=((a,b,c)=>{if(b&&"object"==typeof b||"function"==typeof b)for(let h of f(b))g.call(a,h)||void 0===h||d(a,h,{get:()=>b[h],enumerable:!(c=e(b,h))||c.enumerable});return a})(d({},"__esModule",{value:!0}),h);var k=a.r(236338),l=a.r(580949);async function m(b){let c,d="";try{d=n()}catch(a){c=a}try{let[{getTokenPayload:c,isExpired:e},{refreshToken:f}]=await Promise.all([await a.A(682672),await a.A(966249)]);(!d||e(c(d),b?.expirationBufferMs))&&(await f(b),d=n())}catch(b){let a=c instanceof Error?c.message:"";if(b instanceof Error&&(a=`${a}
|
|
210
250
|
${b.message}`),a)throw new l.VercelOidcTokenError(a);throw b}return d}function n(){let a=(0,k.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!a)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return a}},784628,(a,b,c)=>{"use strict";var d=Object.defineProperty,e=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,g=Object.prototype.hasOwnProperty,h={},i={AccessTokenMissingError:()=>m.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>m.RefreshAccessTokenFailedError,getContext:()=>l.getContext,getVercelOidcToken:()=>k.getVercelOidcToken,getVercelOidcTokenSync:()=>k.getVercelOidcTokenSync,getVercelToken:()=>n.getVercelToken};for(var j in i)d(h,j,{get:i[j],enumerable:!0});b.exports=((a,b,c)=>{if(b&&"object"==typeof b||"function"==typeof b)for(let h of f(b))g.call(a,h)||void 0===h||d(a,h,{get:()=>b[h],enumerable:!(c=e(b,h))||c.enumerable});return a})(d({},"__esModule",{value:!0}),h);var k=a.r(817547),l=a.r(236338),m=a.r(351275),n=a.r(72918)},156956,a=>{"use strict";var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=a.i(527990),y=a.i(652685),z=a.i(794219),A=a.i(912735),B=a.i(784628),C="ai-gateway-transcription.v1";function D(a,b,c){let d=[a,`ai-gateway-auth.${b}`];return(null==c?void 0:c.teamIdOrSlug)&&d.push(`ai-gateway-team.${function(a){let b=new TextEncoder().encode(a),c="";for(let a of b)c+=String.fromCharCode(a);return btoa(c).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}(c.teamIdOrSlug)}`),d}var E={any:z.any,array:z.array,boolean:z.boolean,discriminatedUnion:z.discriminatedUnion,enum:z.enum,literal:z.literal,number:z.number,object:z.object,record:z.record,string:z.string,union:z.union,unknown:z.unknown},F=Symbol.for("vercel.ai.gateway.error"),G=class a extends(c=Error,b=F,c){constructor({message:a,statusCode:c=500,cause:d,generationId:e,isRetryable:f=null!=c&&(408===c||409===c||429===c||c>=500)}){super(e?`${a} [${e}]`:a),this[b]=!0,this.statusCode=c,this.cause=d,this.generationId=e,this.isRetryable=f}static isInstance(b){return a.hasMarker(b)}static hasMarker(a){return"object"==typeof a&&null!==a&&F in a&&!0===a[F]}},H="GatewayAuthenticationError",I=Symbol.for(`vercel.ai.gateway.error.${H}`),J=class a extends(e=G,d=I,e){constructor({message:a="Authentication failed",statusCode:b=401,cause:c,generationId:e}={}){super({message:a,statusCode:b,cause:c,generationId:e}),this[d]=!0,this.name=H,this.type="authentication_error"}static isInstance(a){return G.hasMarker(a)&&I in a}static createContextualError({apiKeyProvided:b,oidcTokenProvided:c,statusCode:d=401,cause:e,generationId:f}){return new a({message:b?`AI Gateway authentication failed: Invalid API key or token.
|
|
211
251
|
|
|
212
252
|
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
@@ -267,4 +307,4 @@ ${b}`:c}else{let a=e.commentBefore;e.commentBefore=a?`${c}
|
|
|
267
307
|
${a}`:c}}if(b){for(let b=0;b<this.errors.length;++b)a.errors.push(this.errors[b]);for(let b=0;b<this.warnings.length;++b)a.warnings.push(this.warnings[b])}else a.errors=this.errors,a.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:l(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(a,b=!1,c=-1){for(let b of a)yield*this.next(b);yield*this.end(b,c)}*next(a){switch(d.env.LOG_STREAM&&console.dir(a,{depth:null}),a.type){case"directive":this.directives.add(a.source,(b,c,d)=>{let e=k(a);e[0]+=b,this.onError(e,"BAD_DIRECTIVE",c,d)}),this.prelude.push(a.source),this.atDirectives=!0;break;case"document":{let b=i.composeDoc(this.options,this.directives,a,this.onError);this.atDirectives&&!b.directives.docStart&&this.onError(a,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(b,!1),this.doc&&(yield this.doc),this.doc=b,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(a.source);break;case"error":{let b=a.source?`${a.message}: ${JSON.stringify(a.source)}`:a.message,c=new g.YAMLParseError(k(a),"UNEXPECTED_TOKEN",b);this.atDirectives||!this.doc?this.errors.push(c):this.doc.errors.push(c);break}case"doc-end":{if(!this.doc){this.errors.push(new g.YAMLParseError(k(a),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let b=j.resolveEnd(a.end,a.offset+a.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),b.comment){let a=this.doc.comment;this.doc.comment=a?`${a}
|
|
268
308
|
${b.comment}`:b.comment}this.doc.range[2]=b.offset;break}default:this.errors.push(new g.YAMLParseError(k(a),"UNEXPECTED_TOKEN",`Unsupported token ${a.type}`))}}*end(a=!1,b=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(a){let a=Object.assign({_directives:this.directives},this.options),c=new f.Document(void 0,a);this.atDirectives&&this.onError(b,"MISSING_CHAR","Missing directives-end indicator line"),c.range=[0,b,b],this.decorate(c,!1),yield c}}}},286888,(a,b,c)=>{"use strict";var d=a.r(871014),e=a.r(121525),f=a.r(725717),g=a.r(688583);function h(a,b){if(b)for(let c of b)switch(c.type){case"space":case"comment":a.push(c);break;case"newline":return a.push(c),!0}return!1}function i(a,b,c){switch(a.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":a.type=c,a.source=b;break;case"block-scalar":{let d=a.props.slice(1),e=b.length;for(let b of("block-scalar-header"===a.props[0].type&&(e-=a.props[0].source.length),d))b.offset+=e;delete a.props,Object.assign(a,{type:c,source:b,end:d});break}case"block-map":case"block-seq":{let d={type:"newline",offset:a.offset+b.length,indent:a.indent,source:"\n"};delete a.items,Object.assign(a,{type:c,source:b,end:[d]});break}default:{let d="indent"in a?a.indent:-1,e="end"in a&&Array.isArray(a.end)?a.end.filter(a=>"space"===a.type||"comment"===a.type||"newline"===a.type):[];for(let b of Object.keys(a))"type"!==b&&"offset"!==b&&delete a[b];Object.assign(a,{type:c,indent:d,source:b,end:e})}}}c.createScalarToken=function(a,b){let{implicitKey:c=!1,indent:d,inFlow:e=!1,offset:f=-1,type:i="PLAIN"}=b,j=g.stringifyString({type:i,value:a},{implicitKey:c,indent:d>0?" ".repeat(d):"",inFlow:e,options:{blockQuote:!0,lineWidth:-1}}),k=b.end??[{type:"newline",offset:-1,indent:d,source:"\n"}];switch(j[0]){case"|":case">":{let a=j.indexOf("\n"),b=j.substring(0,a),c=j.substring(a+1)+"\n",e=[{type:"block-scalar-header",offset:f,indent:d,source:b}];return h(e,k)||e.push({type:"newline",offset:-1,indent:d,source:"\n"}),{type:"block-scalar",offset:f,indent:d,props:e,source:c}}case'"':return{type:"double-quoted-scalar",offset:f,indent:d,source:j,end:k};case"'":return{type:"single-quoted-scalar",offset:f,indent:d,source:j,end:k};default:return{type:"scalar",offset:f,indent:d,source:j,end:k}}},c.resolveAsScalar=function(a,b=!0,c){if(a){let g=(a,b,d)=>{let e="number"==typeof a?a:Array.isArray(a)?a[0]:a.offset;if(c)c(e,b,d);else throw new f.YAMLParseError([e,e+1],b,d)};switch(a.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return e.resolveFlowScalar(a,b,g);case"block-scalar":return d.resolveBlockScalar({options:{strict:b}},a,g)}}return null},c.setScalarValue=function(a,b,c={}){let{afterKey:d=!1,implicitKey:e=!1,inFlow:f=!1,type:j}=c,k="indent"in a?a.indent:null;if(d&&"number"==typeof k&&(k+=2),!j)switch(a.type){case"single-quoted-scalar":j="QUOTE_SINGLE";break;case"double-quoted-scalar":j="QUOTE_DOUBLE";break;case"block-scalar":{let b=a.props[0];if("block-scalar-header"!==b.type)throw Error("Invalid block scalar header");j=">"===b.source[0]?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:j="PLAIN"}let l=g.stringifyString({type:j,value:b},{implicitKey:e||null===k,indent:null!==k&&k>0?" ".repeat(k):"",inFlow:f,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":!function(a,b){let c=b.indexOf("\n"),d=b.substring(0,c),e=b.substring(c+1)+"\n";if("block-scalar"===a.type){let b=a.props[0];if("block-scalar-header"!==b.type)throw Error("Invalid block scalar header");b.source=d,a.source=e}else{let{offset:b}=a,c="indent"in a?a.indent:-1,f=[{type:"block-scalar-header",offset:b,indent:c,source:d}];for(let b of(h(f,"end"in a?a.end:void 0)||f.push({type:"newline",offset:-1,indent:c,source:"\n"}),Object.keys(a)))"type"!==b&&"offset"!==b&&delete a[b];Object.assign(a,{type:"block-scalar",indent:c,props:f,source:e})}}(a,l);break;case'"':i(a,l,"double-quoted-scalar");break;case"'":i(a,l,"single-quoted-scalar");break;default:i(a,l,"scalar")}}},825449,(a,b,c)=>{"use strict";function d(a){switch(a.type){case"block-scalar":{let b="";for(let c of a.props)b+=d(c);return b+a.source}case"block-map":case"block-seq":{let b="";for(let c of a.items)b+=e(c);return b}case"flow-collection":{let b=a.start.source;for(let c of a.items)b+=e(c);for(let c of a.end)b+=c.source;return b}case"document":{let b=e(a);if(a.end)for(let c of a.end)b+=c.source;return b}default:{let b=a.source;if("end"in a&&a.end)for(let c of a.end)b+=c.source;return b}}}function e({start:a,key:b,sep:c,value:f}){let g="";for(let b of a)g+=b.source;if(b&&(g+=d(b)),c)for(let a of c)g+=a.source;return f&&(g+=d(f)),g}c.stringify=a=>"type"in a?d(a):e(a)},402135,(a,b,c)=>{"use strict";let d=Symbol("break visit"),e=Symbol("skip children"),f=Symbol("remove item");function g(a,b){"type"in a&&"document"===a.type&&(a={start:a.start,value:a.value}),function a(b,c,e){let g=e(c,b);if("symbol"==typeof g)return g;for(let h of["key","value"]){let i=c[h];if(i&&"items"in i){for(let c=0;c<i.items.length;++c){let g=a(Object.freeze(b.concat([[h,c]])),i.items[c],e);if("number"==typeof g)c=g-1;else{if(g===d)return d;g===f&&(i.items.splice(c,1),c-=1)}}"function"==typeof g&&"key"===h&&(g=g(c,b))}}return"function"==typeof g?g(c,b):g}(Object.freeze([]),a,b)}g.BREAK=d,g.SKIP=e,g.REMOVE=f,g.itemAtPath=(a,b)=>{let c=a;for(let[a,d]of b){let b=c?.[a];if(!b||!("items"in b))return;c=b.items[d]}return c},g.parentCollection=(a,b)=>{let c=g.itemAtPath(a,b.slice(0,-1)),d=b[b.length-1][0],e=c?.[d];if(e&&"items"in e)return e;throw Error("Parent collection not found")},c.visit=g},2704,(a,b,c)=>{"use strict";var d=a.r(286888),e=a.r(825449),f=a.r(402135);c.createScalarToken=d.createScalarToken,c.resolveAsScalar=d.resolveAsScalar,c.setScalarValue=d.setScalarValue,c.stringify=e.stringify,c.visit=f.visit,c.BOM="\uFEFF",c.DOCUMENT="\x02",c.FLOW_END="\x18",c.SCALAR="\x1f",c.isCollection=a=>!!a&&"items"in a,c.isScalar=a=>!!a&&("scalar"===a.type||"single-quoted-scalar"===a.type||"double-quoted-scalar"===a.type||"block-scalar"===a.type),c.prettyToken=function(a){switch(a){case"\uFEFF":return"<BOM>";case"\x02":return"<DOC>";case"\x18":return"<FLOW_END>";case"\x1f":return"<SCALAR>";default:return JSON.stringify(a)}},c.tokenType=function(a){switch(a){case"\uFEFF":return"byte-order-mark";case"\x02":return"doc-mode";case"\x18":return"flow-error-end";case"\x1f":return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(a[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}},66326,(a,b,c)=>{"use strict";var d=a.r(2704);function e(a){switch(a){case void 0:case" ":case"\n":case"\r":case" ":return!0;default:return!1}}let f=new Set("0123456789ABCDEFabcdef"),g=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),h=new Set(",[]{}"),i=new Set(" ,[]{}\n\r "),j=a=>!a||i.has(a);c.Lexer=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(a,b=!1){if(a){if("string"!=typeof a)throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+a:a,this.lineEndPos=null}this.atEnd=!b;let c=this.next??"stream";for(;c&&(b||this.hasChars(1));)c=yield*this.parseNext(c)}atLineEnd(){let a=this.pos,b=this.buffer[a];for(;" "===b||" "===b;)b=this.buffer[++a];return!b||"#"===b||"\n"===b||"\r"===b&&"\n"===this.buffer[a+1]}charAt(a){return this.buffer[this.pos+a]}continueScalar(a){let b=this.buffer[a];if(this.indentNext>0){let c=0;for(;" "===b;)b=this.buffer[++c+a];if("\r"===b){let b=this.buffer[c+a+1];if("\n"===b||!b&&!this.atEnd)return a+c+1}return"\n"!==b&&!(c>=this.indentNext)&&(b||this.atEnd)?-1:a+c}if("-"===b||"."===b){let b=this.buffer.substr(a,3);if(("---"===b||"..."===b)&&e(this.buffer[a+3]))return -1}return a}getLine(){let a=this.lineEndPos;return(("number"!=typeof a||-1!==a&&a<this.pos)&&(a=this.buffer.indexOf("\n",this.pos),this.lineEndPos=a),-1===a)?this.atEnd?this.buffer.substring(this.pos):null:("\r"===this.buffer[a-1]&&(a-=1),this.buffer.substring(this.pos,a))}hasChars(a){return this.pos+a<=this.buffer.length}setNext(a){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=a,null}peek(a){return this.buffer.substr(this.pos,a)}*parseNext(a){switch(a){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let a=this.getLine();if(null===a)return this.setNext("stream");if(a[0]===d.BOM&&(yield*this.pushCount(1),a=a.substring(1)),"%"===a[0]){let b=a.length,c=a.indexOf("#");for(;-1!==c;){let d=a[c-1];if(" "===d||" "===d){b=c-1;break}c=a.indexOf("#",c+1)}for(;;){let c=a[b-1];if(" "===c||" "===c)b-=1;else break}let d=(yield*this.pushCount(b))+(yield*this.pushSpaces(!0));return yield*this.pushCount(a.length-d),this.pushNewline(),"stream"}if(this.atLineEnd()){let b=yield*this.pushSpaces(!0);return yield*this.pushCount(a.length-b),yield*this.pushNewline(),"stream"}return yield d.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let a=this.charAt(0);if(!a&&!this.atEnd)return this.setNext("line-start");if("-"===a||"."===a){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let a=this.peek(3);if(("---"===a||"..."===a)&&e(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"---"===a?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!e(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[a,b]=this.peek(2);if(!b&&!this.atEnd)return this.setNext("block-start");if(("-"===a||"?"===a||":"===a)&&e(b)){let a=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=a,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let a=this.getLine();if(null===a)return this.setNext("doc");let b=yield*this.pushIndicators();switch(a[b]){case"#":yield*this.pushCount(a.length-b);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(j),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return b+=yield*this.parseBlockScalarHeader(),b+=yield*this.pushSpaces(!0),yield*this.pushCount(a.length-b),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let a,b,c=-1;do(a=yield*this.pushNewline())>0?(b=yield*this.pushSpaces(!1),this.indentValue=c=b):b=0,b+=yield*this.pushSpaces(!0);while(a+b>0)let f=this.getLine();if(null===f)return this.setNext("flow");if((-1!==c&&c<this.indentNext&&"#"!==f[0]||0===c&&(f.startsWith("---")||f.startsWith("..."))&&e(f[3]))&&(c!==this.indentNext-1||1!==this.flowLevel||"]"!==f[0]&&"}"!==f[0]))return this.flowLevel=0,yield d.FLOW_END,yield*this.parseLineStart();let g=0;for(;","===f[g];)g+=yield*this.pushCount(1),g+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(f[g+=yield*this.pushIndicators()]){case void 0:return"flow";case"#":return yield*this.pushCount(f.length-g),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(j),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let a=this.charAt(1);if(this.flowKey||e(a)||","===a)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let a=this.charAt(0),b=this.buffer.indexOf(a,this.pos+1);if("'"===a)for(;-1!==b&&"'"===this.buffer[b+1];)b=this.buffer.indexOf("'",b+2);else for(;-1!==b;){let a=0;for(;"\\"===this.buffer[b-1-a];)a+=1;if(a%2==0)break;b=this.buffer.indexOf('"',b+1)}let c=this.buffer.substring(0,b),d=c.indexOf("\n",this.pos);if(-1!==d){for(;-1!==d;){let a=this.continueScalar(d+1);if(-1===a)break;d=c.indexOf("\n",a)}-1!==d&&(b=d-("\r"===c[d-1]?2:1))}if(-1===b){if(!this.atEnd)return this.setNext("quoted-scalar");b=this.buffer.length}return yield*this.pushToIndex(b+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let a=this.pos;for(;;){let b=this.buffer[++a];if("+"===b)this.blockScalarKeep=!0;else if(b>"0"&&b<="9")this.blockScalarIndent=Number(b)-1;else if("-"!==b)break}return yield*this.pushUntil(a=>e(a)||"#"===a)}*parseBlockScalar(){let a,b=this.pos-1,c=0;b:for(let d=this.pos;a=this.buffer[d];++d)switch(a){case" ":c+=1;break;case"\n":b=d,c=0;break;case"\r":{let a=this.buffer[d+1];if(!a&&!this.atEnd)return this.setNext("block-scalar");if("\n"===a)break}default:break b}if(!a&&!this.atEnd)return this.setNext("block-scalar");if(c>=this.indentNext){-1===this.blockScalarIndent?this.indentNext=c:this.indentNext=this.blockScalarIndent+(0===this.indentNext?1:this.indentNext);do{let a=this.continueScalar(b+1);if(-1===a)break;b=this.buffer.indexOf("\n",a)}while(-1!==b)if(-1===b){if(!this.atEnd)return this.setNext("block-scalar");b=this.buffer.length}}let e=b+1;for(a=this.buffer[e];" "===a;)a=this.buffer[++e];if(" "===a){for(;" "===a||" "===a||"\r"===a||"\n"===a;)a=this.buffer[++e];b=e-1}else if(!this.blockScalarKeep)for(;;){let a=b-1,d=this.buffer[a];"\r"===d&&(d=this.buffer[--a]);let e=a;for(;" "===d;)d=this.buffer[--a];if("\n"===d&&a>=this.pos&&a+1+c>e)b=a;else break}return yield d.SCALAR,yield*this.pushToIndex(b+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let a,b=this.flowLevel>0,c=this.pos-1,f=this.pos-1;for(;a=this.buffer[++f];)if(":"===a){let a=this.buffer[f+1];if(e(a)||b&&h.has(a))break;c=f}else if(e(a)){let d=this.buffer[f+1];if("\r"===a&&("\n"===d?(f+=1,a="\n",d=this.buffer[f+1]):c=f),"#"===d||b&&h.has(d))break;if("\n"===a){let a=this.continueScalar(f+1);if(-1===a)break;f=Math.max(f,a-2)}}else{if(b&&h.has(a))break;c=f}return a||this.atEnd?(yield d.SCALAR,yield*this.pushToIndex(c+1,!0),b?"flow":"doc"):this.setNext("plain-scalar")}*pushCount(a){return a>0?(yield this.buffer.substr(this.pos,a),this.pos+=a,a):0}*pushToIndex(a,b){let c=this.buffer.slice(this.pos,a);return c?(yield c,this.pos+=c.length,c.length):(b&&(yield""),0)}*pushIndicators(){let a=0;for(;;){switch(this.charAt(0)){case"!":a+=yield*this.pushTag(),a+=yield*this.pushSpaces(!0);continue;case"&":a+=yield*this.pushUntil(j),a+=yield*this.pushSpaces(!0);continue;case"-":case"?":case":":{let b=this.flowLevel>0,c=this.charAt(1);if(e(c)||b&&h.has(c)){b?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0);continue}}}break}return a}*pushTag(){if("<"===this.charAt(1)){let a=this.pos+2,b=this.buffer[a];for(;!e(b)&&">"!==b;)b=this.buffer[++a];return yield*this.pushToIndex(">"===b?a+1:a,!1)}{let a=this.pos+1,b=this.buffer[a];for(;b;)if(g.has(b))b=this.buffer[++a];else if("%"===b&&f.has(this.buffer[a+1])&&f.has(this.buffer[a+2]))b=this.buffer[a+=3];else break;return yield*this.pushToIndex(a,!1)}}*pushNewline(){let a=this.buffer[this.pos];return"\n"===a?yield*this.pushCount(1):"\r"===a&&"\n"===this.charAt(1)?yield*this.pushCount(2):0}*pushSpaces(a){let b,c=this.pos-1;do b=this.buffer[++c];while(" "===b||a&&" "===b)let d=c-this.pos;return d>0&&(yield this.buffer.substr(this.pos,d),this.pos=c),d}*pushUntil(a){let b=this.pos,c=this.buffer[b];for(;!a(c);)c=this.buffer[++b];return yield*this.pushToIndex(b,!1)}}},746987,(a,b,c)=>{"use strict";c.LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=a=>this.lineStarts.push(a),this.linePos=a=>{let b=0,c=this.lineStarts.length;for(;b<c;){let d=b+c>>1;this.lineStarts[d]<a?b=d+1:c=d}if(this.lineStarts[b]===a)return{line:b+1,col:1};if(0===b)return{line:0,col:a};let d=this.lineStarts[b-1];return{line:b,col:a-d+1}}}}},309575,(a,b,c)=>{"use strict";var d=a.r(605365),e=a.r(2704),f=a.r(66326);function g(a,b){for(let c=0;c<a.length;++c)if(a[c].type===b)return!0;return!1}function h(a){for(let b=0;b<a.length;++b)switch(a[b].type){case"space":case"comment":case"newline":break;default:return b}return -1}function i(a){switch(a?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function j(a){switch(a.type){case"document":return a.start;case"block-map":{let b=a.items[a.items.length-1];return b.sep??b.start}case"block-seq":return a.items[a.items.length-1].start;default:return[]}}function k(a){if(0===a.length)return[];let b=a.length;b:for(;--b>=0;)switch(a[b].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break b}for(;a[++b]?.type==="space";);return a.splice(b,a.length)}function l(a,b){if(b.length<1e5)Array.prototype.push.apply(a,b);else for(let c=0;c<b.length;++c)a.push(b[c])}function m(a){if("flow-seq-start"===a.start.type)for(let b of a.items)!b.sep||b.value||g(b.start,"explicit-key-ind")||g(b.sep,"map-value-ind")||(b.key&&(b.value=b.key),delete b.key,i(b.value)?b.value.end?l(b.value.end,b.sep):b.value.end=b.sep:l(b.start,b.sep),delete b.sep)}c.Parser=class{constructor(a){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new f.Lexer,this.onNewLine=a}*parse(a,b=!1){for(let c of(this.onNewLine&&0===this.offset&&this.onNewLine(0),this.lexer.lex(a,b)))yield*this.next(c);b||(yield*this.end())}*next(a){if(this.source=a,d.env.LOG_TOKENS&&console.log("|",e.prettyToken(a)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=a.length;return}let b=e.tokenType(a);if(b)if("scalar"===b)this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=b,yield*this.step(),b){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+a.length);break;case"space":this.atNewLine&&" "===a[0]&&(this.indent+=a.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=a.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=a.length}else{let b=`Not a YAML token: ${a}`;yield*this.pop({type:"error",offset:this.offset,message:b,source:a}),this.offset+=a.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let a=this.peek(1);if("doc-end"===this.type&&a?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!a)return yield*this.stream();switch(a.type){case"document":return yield*this.document(a);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(a);case"block-scalar":return yield*this.blockScalar(a);case"block-map":return yield*this.blockMap(a);case"block-seq":return yield*this.blockSequence(a);case"flow-collection":return yield*this.flowCollection(a);case"doc-end":return yield*this.documentEnd(a)}yield*this.pop()}peek(a){return this.stack[this.stack.length-a]}*pop(a){let b=a??this.stack.pop();if(b)if(0===this.stack.length)yield b;else{let a=this.peek(1);switch("block-scalar"===b.type?b.indent="indent"in a?a.indent:0:"flow-collection"===b.type&&"document"===a.type&&(b.indent=0),"flow-collection"===b.type&&m(b),a.type){case"document":a.value=b;break;case"block-scalar":a.props.push(b);break;case"block-map":{let c=a.items[a.items.length-1];if(c.value){a.items.push({start:[],key:b,sep:[]}),this.onKeyLine=!0;return}if(c.sep)c.value=b;else{Object.assign(c,{key:b,sep:[]}),this.onKeyLine=!c.explicitKey;return}break}case"block-seq":{let c=a.items[a.items.length-1];c.value?a.items.push({start:[],value:b}):c.value=b;break}case"flow-collection":{let c=a.items[a.items.length-1];!c||c.value?a.items.push({start:[],key:b,sep:[]}):c.sep?c.value=b:Object.assign(c,{key:b,sep:[]});return}default:yield*this.pop(),yield*this.pop(b)}if(("document"===a.type||"block-map"===a.type||"block-seq"===a.type)&&("block-map"===b.type||"block-seq"===b.type)){let c=b.items[b.items.length-1];c&&!c.sep&&!c.value&&c.start.length>0&&-1===h(c.start)&&(0===b.indent||c.start.every(a=>"comment"!==a.type||a.indent<b.indent))&&("document"===a.type?a.end=c.start:a.items.push({start:c.start}),b.items.splice(-1,1))}}else yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let a={type:"document",offset:this.offset,start:[]};"doc-start"===this.type&&a.start.push(this.sourceToken),this.stack.push(a);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(a){if(a.value)return yield*this.lineEnd(a);switch(this.type){case"doc-start":-1!==h(a.start)?(yield*this.pop(),yield*this.step()):a.start.push(this.sourceToken);return;case"anchor":case"tag":case"space":case"comment":case"newline":a.start.push(this.sourceToken);return}let b=this.startBlockValue(a);b?this.stack.push(b):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(a){if("map-value-ind"===this.type){let b,c=k(j(this.peek(2)));a.end?((b=a.end).push(this.sourceToken),delete a.end):b=[this.sourceToken];let d={type:"block-map",offset:a.offset,indent:a.indent,items:[{start:c,key:a,sep:b}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=d}else yield*this.lineEnd(a)}*blockScalar(a){switch(this.type){case"space":case"comment":case"newline":a.props.push(this.sourceToken);return;case"scalar":if(a.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let a=this.source.indexOf("\n")+1;for(;0!==a;)this.onNewLine(this.offset+a),a=this.source.indexOf("\n",a)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(a){let b=a.items[a.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,b.value){let c="end"in b.value?b.value.end:void 0,d=Array.isArray(c)?c[c.length-1]:void 0;d?.type==="comment"?c?.push(this.sourceToken):a.items.push({start:[this.sourceToken]})}else b.sep?b.sep.push(this.sourceToken):b.start.push(this.sourceToken);return;case"space":case"comment":if(b.value)a.items.push({start:[this.sourceToken]});else if(b.sep)b.sep.push(this.sourceToken);else{if(this.atIndentedComment(b.start,a.indent)){let c=a.items[a.items.length-2],d=c?.value?.end;if(Array.isArray(d)){l(d,b.start),d.push(this.sourceToken),a.items.pop();return}}b.start.push(this.sourceToken)}return}if(this.indent>=a.indent){let c=!this.onKeyLine&&this.indent===a.indent,d=c&&(b.sep||b.explicitKey)&&"seq-item-ind"!==this.type,e=[];if(d&&b.sep&&!b.value){let c=[];for(let d=0;d<b.sep.length;++d){let e=b.sep[d];switch(e.type){case"newline":c.push(d);break;case"space":break;case"comment":e.indent>a.indent&&(c.length=0);break;default:c.length=0}}c.length>=2&&(e=b.sep.splice(c[1]))}switch(this.type){case"anchor":case"tag":d||b.value?(e.push(this.sourceToken),a.items.push({start:e}),this.onKeyLine=!0):b.sep?b.sep.push(this.sourceToken):b.start.push(this.sourceToken);return;case"explicit-key-ind":b.sep||b.explicitKey?d||b.value?(e.push(this.sourceToken),a.items.push({start:e,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}):(b.start.push(this.sourceToken),b.explicitKey=!0),this.onKeyLine=!0;return;case"map-value-ind":if(b.explicitKey)if(b.sep)if(b.value)a.items.push({start:[],key:null,sep:[this.sourceToken]});else if(g(b.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]});else if(i(b.key)&&!g(b.sep,"newline")){let a=k(b.start),c=b.key,d=b.sep;d.push(this.sourceToken),delete b.key,delete b.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:c,sep:d}]})}else e.length>0?b.sep=b.sep.concat(e,this.sourceToken):b.sep.push(this.sourceToken);else if(g(b.start,"newline"))Object.assign(b,{key:null,sep:[this.sourceToken]});else{let a=k(b.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else b.sep?b.value||d?a.items.push({start:e,key:null,sep:[this.sourceToken]}):g(b.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):b.sep.push(this.sourceToken):Object.assign(b,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let c=this.flowScalar(this.type);d||b.value?(a.items.push({start:e,key:c,sep:[]}),this.onKeyLine=!0):b.sep?this.stack.push(c):(Object.assign(b,{key:c,sep:[]}),this.onKeyLine=!0);return}default:{let d=this.startBlockValue(a);if(d){if("block-seq"===d.type){if(!b.explicitKey&&b.sep&&!g(b.sep,"newline"))return void(yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source}))}else c&&a.items.push({start:e});this.stack.push(d);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(a){let b=a.items[a.items.length-1];switch(this.type){case"newline":if(b.value){let c="end"in b.value?b.value.end:void 0,d=Array.isArray(c)?c[c.length-1]:void 0;d?.type==="comment"?c?.push(this.sourceToken):a.items.push({start:[this.sourceToken]})}else b.start.push(this.sourceToken);return;case"space":case"comment":if(b.value)a.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(b.start,a.indent)){let c=a.items[a.items.length-2],d=c?.value?.end;if(Array.isArray(d)){l(d,b.start),d.push(this.sourceToken),a.items.pop();return}}b.start.push(this.sourceToken)}return;case"anchor":case"tag":if(b.value||this.indent<=a.indent)break;b.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==a.indent)break;b.value||g(b.start,"seq-item-ind")?a.items.push({start:[this.sourceToken]}):b.start.push(this.sourceToken);return}if(this.indent>a.indent){let b=this.startBlockValue(a);if(b)return void this.stack.push(b)}yield*this.pop(),yield*this.step()}*flowCollection(a){let b=a.items[a.items.length-1];if("flow-error-end"===this.type){let a;do yield*this.pop(),a=this.peek(1);while(a?.type==="flow-collection")}else if(0===a.end.length){switch(this.type){case"comma":case"explicit-key-ind":!b||b.sep?a.items.push({start:[this.sourceToken]}):b.start.push(this.sourceToken);return;case"map-value-ind":!b||b.value?a.items.push({start:[],key:null,sep:[this.sourceToken]}):b.sep?b.sep.push(this.sourceToken):Object.assign(b,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!b||b.value?a.items.push({start:[this.sourceToken]}):b.sep?b.sep.push(this.sourceToken):b.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let c=this.flowScalar(this.type);!b||b.value?a.items.push({start:[],key:c,sep:[]}):b.sep?this.stack.push(c):Object.assign(b,{key:c,sep:[]});return}case"flow-map-end":case"flow-seq-end":a.end.push(this.sourceToken);return}let c=this.startBlockValue(a);c?this.stack.push(c):(yield*this.pop(),yield*this.step())}else{let b=this.peek(2);if("block-map"!==b.type||("map-value-ind"!==this.type||b.indent!==a.indent)&&("newline"!==this.type||b.items[b.items.length-1].sep))if("map-value-ind"===this.type&&"flow-collection"!==b.type){let c=k(j(b));m(a);let d=a.end.splice(1,a.end.length);d.push(this.sourceToken);let e={type:"block-map",offset:a.offset,indent:a.indent,items:[{start:c,key:a,sep:d}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=e}else yield*this.lineEnd(a);else yield*this.pop(),yield*this.step()}}flowScalar(a){if(this.onNewLine){let a=this.source.indexOf("\n")+1;for(;0!==a;)this.onNewLine(this.offset+a),a=this.source.indexOf("\n",a)+1}return{type:a,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(a){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let b=k(j(a));return b.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:b,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let b=k(j(a));return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:b,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(a,b){return"comment"===this.type&&!(this.indent<=b)&&a.every(a=>"newline"===a.type||"space"===a.type)}*documentEnd(a){"doc-mode"!==this.type&&(a.end?a.end.push(this.sourceToken):a.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop()))}*lineEnd(a){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:a.end?a.end.push(this.sourceToken):a.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop())}}}},5013,(a,b,c)=>{"use strict";var d=a.r(719662),e=a.r(885774),f=a.r(725717),g=a.r(918114),h=a.r(927267),i=a.r(746987),j=a.r(309575);function k(a){let b=!1!==a.prettyErrors;return{lineCounter:a.lineCounter||b&&new i.LineCounter||null,prettyErrors:b}}function l(a,b={}){let{lineCounter:c,prettyErrors:e}=k(b),g=new j.Parser(c?.addNewLine),h=new d.Composer(b),i=null;for(let b of h.compose(g.parse(a),!0,a.length))if(i){if("silent"!==i.options.logLevel){i.errors.push(new f.YAMLParseError(b.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}else i=b;return e&&c&&(i.errors.forEach(f.prettifyError(a,c)),i.warnings.forEach(f.prettifyError(a,c))),i}c.parse=function(a,b,c){let d;"function"==typeof b?d=b:void 0===c&&b&&"object"==typeof b&&(c=b);let e=l(a,c);if(!e)return null;if(e.warnings.forEach(a=>g.warn(e.options.logLevel,a)),e.errors.length>0)if("silent"!==e.options.logLevel)throw e.errors[0];else e.errors=[];return e.toJS(Object.assign({reviver:d},c))},c.parseAllDocuments=function(a,b={}){let{lineCounter:c,prettyErrors:e}=k(b),g=new j.Parser(c?.addNewLine),h=new d.Composer(b),i=Array.from(h.compose(g.parse(a)));if(e&&c)for(let b of i)b.errors.forEach(f.prettifyError(a,c)),b.warnings.forEach(f.prettifyError(a,c));return i.length>0?i:Object.assign([],{empty:!0},h.streamInfo())},c.parseDocument=l,c.stringify=function(a,b,c){let d=null;if("function"==typeof b||Array.isArray(b)?d=b:void 0===c&&b&&(c=b),"string"==typeof c&&(c=c.length),"number"==typeof c){let a=Math.round(c);c=a<1?void 0:a>8?{indent:8}:{indent:a}}if(void 0===a){let{keepUndefined:a}=c??b??{};if(!a)return}return h.isDocument(a)&&!d?a.toString(c):new e.Document(a,d,c).toString(c)}},622650,(a,b,c)=>{"use strict";var d=a.r(719662),e=a.r(885774),f=a.r(798027),g=a.r(725717),h=a.r(421562),i=a.r(927267),j=a.r(417602),k=a.r(427853),l=a.r(147544),m=a.r(907621),n=a.r(2704),o=a.r(66326),p=a.r(746987),q=a.r(309575),r=a.r(5013),s=a.r(685927);c.Composer=d.Composer,c.Document=e.Document,c.Schema=f.Schema,c.YAMLError=g.YAMLError,c.YAMLParseError=g.YAMLParseError,c.YAMLWarning=g.YAMLWarning,c.Alias=h.Alias,c.isAlias=i.isAlias,c.isCollection=i.isCollection,c.isDocument=i.isDocument,c.isMap=i.isMap,c.isNode=i.isNode,c.isPair=i.isPair,c.isScalar=i.isScalar,c.isSeq=i.isSeq,c.Pair=j.Pair,c.Scalar=k.Scalar,c.YAMLMap=l.YAMLMap,c.YAMLSeq=m.YAMLSeq,c.CST=n,c.Lexer=o.Lexer,c.LineCounter=p.LineCounter,c.Parser=q.Parser,c.parse=r.parse,c.parseAllDocuments=r.parseAllDocuments,c.parseDocument=r.parseDocument,c.stringify=r.stringify,c.visit=s.visit,c.visitAsync=s.visitAsync}];
|
|
269
309
|
|
|
270
|
-
//# sourceMappingURL=
|
|
310
|
+
//# sourceMappingURL=_0nk80t6._.js.map
|