thursday-agent 0.1.2 → 0.2.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 +1 -0
- package/.next/build-manifest.json +3 -3
- package/.next/prerender-manifest.json +3 -3
- package/.next/routes-manifest.json +6 -0
- package/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +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 +13 -13
- package/.next/server/app/_not-found.segments/_full.segment.rsc +13 -13
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +12 -12
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/api/artifact/route.js +1 -1
- package/.next/server/app/api/artifact/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/notes/route/app-paths-manifest.json +3 -0
- package/.next/server/app/api/bot/notes/route/build-manifest.json +12 -0
- package/.next/server/app/api/bot/notes/route/server-reference-manifest.json +4 -0
- package/.next/server/app/api/bot/notes/route.js +14 -0
- package/.next/server/app/api/bot/notes/route.js.map +5 -0
- package/.next/server/app/api/bot/notes/route.js.nft.json +1 -0
- package/.next/server/app/api/bot/notes/route_client-reference-manifest.js +3 -0
- 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/task/[id]/route.js +6 -6
- package/.next/server/app/api/bot/task/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/task/route.js +6 -6
- package/.next/server/app/api/bot/task/route.js.nft.json +1 -1
- package/.next/server/app/api/config/route.js +3 -3
- package/.next/server/app/api/config/route.js.nft.json +1 -1
- package/.next/server/app/api/events/route.js +1 -1
- package/.next/server/app/api/events/route.js.nft.json +1 -1
- package/.next/server/app/api/file/[...path]/route.js +1 -1
- package/.next/server/app/api/file/[...path]/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/catalog/route.js +6 -6
- package/.next/server/app/api/llm-model/catalog/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/route.js +3 -3
- package/.next/server/app/api/llm-model/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/[name]/route.js +3 -3
- package/.next/server/app/api/mcp/[name]/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/oauth/callback/route.js +5 -5
- package/.next/server/app/api/mcp/oauth/callback/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/route.js +3 -3
- package/.next/server/app/api/mcp/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/tools/route.js +3 -3
- package/.next/server/app/api/mcp/tools/route.js.nft.json +1 -1
- package/.next/server/app/api/memory/route.js +7 -7
- package/.next/server/app/api/memory/route.js.nft.json +1 -1
- package/.next/server/app/api/memory/tidy/route.js +10 -11
- package/.next/server/app/api/memory/tidy/route.js.nft.json +1 -1
- package/.next/server/app/api/skills/[source]/[name]/route.js +1 -1
- package/.next/server/app/api/skills/[source]/[name]/route.js.nft.json +1 -1
- package/.next/server/app/api/skills/route.js +1 -1
- package/.next/server/app/api/skills/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/call/route.js +8 -8
- package/.next/server/app/api/thursday/call/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/skills/route.js +8 -8
- package/.next/server/app/api/thursday/skills/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/tool-call/route.js +11 -12
- package/.next/server/app/api/thursday/tool-call/route.js.nft.json +1 -1
- package/.next/server/app/api/workspace/route.js +1 -1
- package/.next/server/app/api/workspace/route.js.nft.json +1 -1
- package/.next/server/app/artifact/[...path]/page/server-reference-manifest.json +1 -1
- package/.next/server/app/artifact/[...path]/page.js +3 -3
- 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/page/server-reference-manifest.json +63 -41
- package/.next/server/app/page.js +7 -7
- 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 +1 -0
- package/.next/server/chunks/0d-b_next_dist_server_app-render_after-task-async-storage_external_0-exn7p.js +3 -0
- package/.next/server/chunks/{[root-of-the-server]__0t_dqaj._.js → [root-of-the-server]__0-npkh_._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__005var5._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__019dx9f._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__02va5wz._.js +3 -0
- package/.next/server/chunks/{[root-of-the-server]__1mzp_el._.js → [root-of-the-server]__04_8spk._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__06t77t4._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0bed6hu._.js +4 -4
- package/.next/server/chunks/[root-of-the-server]__0cro2dz._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__0emr6go._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0le4d-p._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0m8ywyo._.js +5 -5
- package/.next/server/chunks/{[root-of-the-server]__113fqg5._.js → [root-of-the-server]__0p32jfz._.js} +3 -3
- package/.next/server/chunks/[root-of-the-server]__0phdgco._.js +4 -4
- package/.next/server/chunks/[root-of-the-server]__0wvgrsl._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__11j52t0._.js +5 -0
- package/.next/server/chunks/{[root-of-the-server]__0j_n5l3._.js → [root-of-the-server]__1692zrv._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__16thabu._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__173nhwf._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__1bn73ih._.js +10 -0
- package/.next/server/chunks/[root-of-the-server]__1bqhuh9._.js +4 -4
- package/.next/server/chunks/[root-of-the-server]__1ccon1w._.js +10 -0
- package/.next/server/chunks/[root-of-the-server]__1cqizfq._.js +1 -1
- package/.next/server/chunks/{[root-of-the-server]__1u_qvc7._.js → [root-of-the-server]__1fboj2j._.js} +2 -2
- package/.next/server/chunks/{[root-of-the-server]__1dow0bz._.js → [root-of-the-server]__1oli73c._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__1txedx6._.js +4 -4
- package/.next/server/chunks/[root-of-the-server]__1untqv8._.js +5 -0
- package/.next/server/chunks/_0-73of8._.js +55 -0
- package/.next/server/chunks/{_2050gwn._.js → _00_584r._.js} +66 -28
- package/.next/server/chunks/{_0y8is-s._.js → _03a0897._.js} +1 -1
- package/.next/server/chunks/_05h2cii._.js +1 -1
- package/.next/server/chunks/_06mxlgn._.js +1 -1
- package/.next/server/chunks/_0a351g7._.js +1 -1
- package/.next/server/chunks/{_0hin38_._.js → _0khihjk._.js} +5 -5
- package/.next/server/chunks/_0kjjmag._.js +1 -1
- package/.next/server/chunks/{_1t8fv7b._.js → _0n74zsf._.js} +5 -5
- package/.next/server/chunks/_0nn99o2._.js +3 -0
- package/.next/server/chunks/_0pppbb5._.js +10 -6
- package/.next/server/chunks/{_1icgbi8._.js → _0rnf-6n._.js} +5 -5
- package/.next/server/chunks/_0u10wmw._.js +55 -0
- package/.next/server/chunks/{_0kl37zl._.js → _0vnutv9._.js} +1 -1
- package/.next/server/chunks/_0wp4le3._.js +1 -1
- package/.next/server/chunks/_0y5fg-x._.js +1 -1
- package/.next/server/chunks/_106co2o._.js +3 -0
- package/.next/server/chunks/_12bbv5i._.js +10 -6
- package/.next/server/chunks/_15hq89o._.js +1 -1
- package/.next/server/chunks/_15q1pig._.js +1 -1
- package/.next/server/chunks/_18-1wcc._.js +55 -0
- package/.next/server/chunks/_19wg5yn._.js +138 -0
- package/.next/server/chunks/_1_5mnq4._.js +18 -0
- package/.next/server/chunks/_1bt95p9._.js +55 -0
- package/.next/server/chunks/_1cbk7ms._.js +9 -9
- package/.next/server/chunks/_1drgfx4._.js +18 -0
- package/.next/server/chunks/_1drv2et._.js +10 -6
- package/.next/server/chunks/{_10qam6o._.js → _1e48czp._.js} +5 -5
- package/.next/server/chunks/{_1skgy7b._.js → _1kg70wc._.js} +5 -5
- package/.next/server/chunks/_1php4eq._.js +1 -1
- package/.next/server/chunks/_1rysr-r._.js +10 -0
- package/.next/server/chunks/_1u3rwbr._.js +3 -0
- package/.next/server/chunks/_1x7p319._.js +1 -1
- package/.next/server/chunks/_1yuv4vp._.js +1 -1
- package/.next/server/chunks/_next-internal_server_app_api_bot_notes_route_actions_0qcsyu7.js +3 -0
- package/.next/server/chunks/config_ts_1g4sz5o._.js +1 -1
- package/.next/server/chunks/features_bot_task_query_ts_11xuzl3._.js +1 -1
- package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_0228f43._.js → node_modules_consola_dist_chunks_prompt_mjs_02s3hjt._.js} +1 -1
- package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_0ir-vo2._.js → node_modules_consola_dist_chunks_prompt_mjs_06067w6._.js} +1 -1
- package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_0otw8ef._.js → node_modules_consola_dist_chunks_prompt_mjs_096ais_._.js} +1 -1
- package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_0tf290y._.js → node_modules_consola_dist_chunks_prompt_mjs_0a1rd09._.js} +1 -1
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_0gzvgfv._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_0j61-ma._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_0tvkfgh._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_11zjo-1._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1pycqsq._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1tpvamf._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1y9-wcr._.js +3 -0
- package/.next/server/chunks/ssr/[externals]__0dizgek._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0f6s48x._.js +1 -1
- package/.next/server/chunks/ssr/[root-of-the-server]__0m1b5ky._.js +3 -0
- package/.next/server/chunks/ssr/{[root-of-the-server]__0dfwvr4._.js → [root-of-the-server]__0un-erv._.js} +2 -2
- package/.next/server/chunks/ssr/[root-of-the-server]__1-mnhyd._.js +5 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1bww500._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1mzi-ju._.js +1 -1
- package/.next/server/chunks/ssr/[root-of-the-server]__1qfqvmg._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1vcdast._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1xwnu-h._.js +3 -0
- package/.next/server/chunks/ssr/_03webdr._.js +3 -0
- package/.next/server/chunks/ssr/{_0gd4vaa._.js → _040sk32._.js} +71 -29
- package/.next/server/chunks/ssr/_077-g6s._.js +1 -1
- package/.next/server/chunks/ssr/{_0lc_7c8._.js → _09ja_w1._.js} +2 -2
- package/.next/server/chunks/ssr/{_1dcxzqe._.js → _0f_b_9s._.js} +2 -2
- package/.next/server/chunks/ssr/_0h7zdni._.js +1 -1
- package/.next/server/chunks/ssr/_0lu1n_x._.js +3 -0
- package/.next/server/chunks/ssr/_0sf1isi._.js +1 -1
- package/.next/server/chunks/ssr/_0su6_08._.js +3 -0
- package/.next/server/chunks/ssr/{_0nso8tp._.js → _0w5bgak._.js} +2 -2
- package/.next/server/chunks/ssr/{_19_o9d-._.js → _0x_nu5e._.js} +2 -2
- package/.next/server/chunks/ssr/_1-teee5._.js +3 -3
- package/.next/server/chunks/ssr/_13punpm._.js +1 -1
- package/.next/server/chunks/ssr/{_0ay6b01._.js → _1ciyoo3._.js} +2 -2
- package/.next/server/chunks/ssr/_1e-dgz0._.js +1 -1
- package/.next/server/chunks/ssr/_1fq7zgb._.js +1 -1
- package/.next/server/chunks/ssr/{_0cvjbuz._.js → _1g6l4uj._.js} +2 -2
- package/.next/server/chunks/ssr/{_0q_2f2x._.js → _1lip4th._.js} +2 -2
- package/.next/server/chunks/ssr/_1m3bsfr._.js +3 -0
- package/.next/server/chunks/ssr/_1mznrxk._.js +1 -1
- package/.next/server/chunks/ssr/_1ruzehw._.js +3 -0
- package/.next/server/chunks/ssr/_1vyd1ji._.js +3 -0
- package/.next/server/chunks/ssr/features_bot_components_bot-setting_tsx_01ajft6._.js +2 -2
- package/.next/server/chunks/ssr/features_config_components_14jqgy4._.js +1 -1
- package/.next/server/chunks/ssr/features_config_components_config-setting_tsx_0xfwqdg._.js +1 -1
- 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/lib_realtime_12wg_dd._.js +27 -0
- package/.next/server/chunks/ssr/lib_realtime_15h_v1v._.js +27 -0
- package/.next/server/chunks/ssr/{node_modules_108wd2o._.js → node_modules_004qlr4._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1ub40gk._.js → node_modules_01qnv-a._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1y8_3vg._.js → node_modules_04n7mjs._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0_j7-g4._.js → node_modules_08d8bke._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0y2-av4._.js → node_modules_09xhur7._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_043-236._.js → node_modules_0_n241r._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0ls96je._.js → node_modules_0iz1rzd._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0xwx4u-._.js → node_modules_0kl7-tn._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1jatz7w._.js → node_modules_0kxz4gt._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1t0y5jt._.js → node_modules_0lrjk5t._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_13f2md6._.js → node_modules_0m93zeg._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1nhw9qg._.js → node_modules_0n1kj4p._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1k29j1j._.js → node_modules_0ndvxub._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_16i4o_3._.js → node_modules_13r44jq._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0fbw5-u._.js → node_modules_17lrt3y._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1d-is1o._.js → node_modules_18_dk7_._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1hn_sd5._.js → node_modules_19dp7ko._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_20ynonm._.js → node_modules_1dwguw_._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_00d6675._.js → node_modules_1hd-5tv._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1ee8gav._.js → node_modules_1hn8z1f._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0bue6gy._.js → node_modules_1n5ygqe._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1_588_4._.js → node_modules_1q0p85z._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0ipn1ho._.js → node_modules_1toafc-._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0_fvxnt._.js → node_modules_1xyd7ov._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1v0077l._.js → node_modules_1zu988w._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_06kvvuo._.js → node_modules_20yebtj._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_092s8nx._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0m9a4y0._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1nvexgu._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_13w_wy9._.js} +1 -1
- package/.next/server/chunks/ssr/node_modules_consola_dist_chunks_prompt_mjs_05cwqv2._.js +47 -0
- 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 +64 -42
- package/.next/static/chunks/05b6nx_o3_f_n.js +1 -0
- package/.next/static/chunks/{3aquirz5h71da.js → 07kl352c-lvcz.js} +1 -1
- package/.next/static/chunks/0dmns-gi0raa4.js +1 -0
- package/.next/static/chunks/0oc4_xoia77dg.css +1 -0
- package/.next/static/chunks/0pheo8m3a-rzi.js +1 -0
- package/.next/static/chunks/{2ihkf6l2jowo9.js → 18vhba44l1fc9.js} +3 -3
- package/.next/static/chunks/19i8h2t-5evjx.js +1 -0
- package/.next/static/chunks/{1gy3bbv7usnjo.js → 1c5fcj473025q.js} +1 -1
- package/.next/static/chunks/1pi_hbmjw-f-z.js +1 -0
- package/.next/static/chunks/{0tydnn2kybibk.js → 1twt6k09vg4np.js} +1 -1
- package/.next/static/chunks/{21rk8w7bda-su.js → 28gotuisldmom.js} +1 -1
- package/.next/static/chunks/{3xxa2j56-f3nm.js → 2998p0y7k1c8z.js} +1 -1
- package/.next/static/chunks/2l233xfycjpd8.js +1 -0
- package/.next/static/chunks/2p5n7pa3c40t-.js +2 -0
- package/.next/static/chunks/2ru1q132af7h7.js +1 -0
- package/.next/static/chunks/{2fq_86jvq9ymq.js → 2t8wqycwg3y04.js} +2 -2
- package/.next/static/chunks/32z_ypgtchw48.js +1 -0
- package/.next/static/chunks/{247d-r95j8xs0.js → 33pyjb3xd1iez.js} +1 -1
- package/.next/static/chunks/3786h5vayt80-.js +28 -0
- package/.next/static/chunks/3_h9txt3tq8t8.js +28 -0
- package/.next/static/chunks/{1khakdu_iuedc.js → 3ard_noqapnw1.js} +1 -1
- package/.next/static/chunks/{1fr5m75pwtyic.js → 3omud5xunrk1f.js} +1 -1
- package/.next/static/chunks/42dnrkbph9e-1.js +1 -0
- package/app/api/events/app-event.client.ts +24 -0
- package/app/api/events/app-event.server.ts +45 -0
- package/app/api/events/app-event.ts +44 -0
- package/app/api/llm-model/catalog/route.ts +12 -0
- package/app/api/llm-model/route.ts +21 -0
- package/app/api/query-key.ts +144 -0
- package/app/api/thursday/tool-call/route.ts +67 -0
- package/components/ui/button-group.tsx +45 -0
- package/components/ui/custom-icon.tsx +259 -0
- package/components/ui/dropdown-menu.tsx +271 -0
- package/components/ui/folded-text.tsx +68 -0
- package/components/ui/input-group.tsx +157 -0
- package/components/ui/json-view.tsx +240 -0
- package/components/ui/shiny-text.tsx +141 -0
- package/components/ui/text-type.tsx +213 -0
- package/components/ui/theme-sync.tsx +9 -0
- package/database/migrations/{20260908030742_rainy_marvel_zombies → 20260909060813_optimal_sabretooth}/migration.sql +7 -0
- package/database/migrations/{20260908030742_rainy_marvel_zombies → 20260909060813_optimal_sabretooth}/snapshot.json +54 -1
- package/database/migrations/20260909063821_bitter_tenebrous/migration.sql +1 -0
- package/database/migrations/20260909063821_bitter_tenebrous/snapshot.json +1285 -0
- package/docs/how-it-works.md +59 -0
- package/docs/images/keeps-going.png +0 -0
- package/docs/images/task-thread.png +0 -0
- package/docs/images/two-minds.png +0 -0
- package/features/ai/load-tools.ts +55 -5
- package/features/ai/prompts/bot.prompt.ts +121 -26
- package/features/ai/prompts/memory-tidy.prompt.ts +7 -1
- package/features/ai/prompts/prompt-helper.ts +31 -5
- package/features/ai/prompts/thursday.prompt.ts +2 -0
- package/features/ai/tools/bot.tool.ts +37 -18
- package/features/ai/tools/mcp.tool.ts +5 -5
- package/features/ai/tools/memory.tool.ts +17 -10
- package/features/ai/tools/studio.tool.ts +5 -5
- package/features/ai/tools/tool-name.ts +2 -0
- package/features/ai/tools/workspace.tool.ts +33 -5
- package/features/bot/bot.action.ts +31 -4
- package/features/bot/bot.notes.ts +120 -0
- package/features/bot/bot.query.ts +56 -1
- package/features/bot/bot.run.ts +43 -3
- package/features/bot/bot.runner.ts +94 -20
- package/features/bot/bot.schema.ts +17 -0
- package/features/bot/components/bot-room.tsx +405 -306
- package/features/bot/components/bot-setting.tsx +123 -20
- package/features/bot/task.query.ts +18 -5
- package/features/memory/components/memory-setting.tsx +11 -2
- package/features/memory/memory.query.ts +9 -2
- package/features/memory/memory.schema.ts +30 -0
- package/features/skills/components/skills-setting.tsx +9 -1
- package/features/workspace/workspace.ts +136 -3
- package/hooks/use-draft.ts +37 -0
- package/hooks/use-hotkey.ts +105 -0
- package/hooks/use-object-state.ts +51 -0
- package/hooks/use-on-visible.ts +72 -0
- package/hooks/use-theme.ts +106 -0
- package/hooks/use-wake-word.ts +262 -0
- package/lib/realtime/realtime.driver.ts +34 -1
- package/lib/realtime/realtime.protocol.ts +6 -0
- package/lib/sandbox.ts +9 -1
- package/lib/tokens.ts +19 -0
- package/package.json +1 -1
- package/.next/server/chunks/[root-of-the-server]__02kt8yn._.js +0 -10
- package/.next/server/chunks/[root-of-the-server]__0h59di-._.js +0 -5
- package/.next/server/chunks/[root-of-the-server]__0qjqtwo._.js +0 -5
- package/.next/server/chunks/[root-of-the-server]__0yk6s3w._.js +0 -5
- package/.next/server/chunks/[root-of-the-server]__0z3gelv._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__11w_7_3._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1_0q_9w._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1gmn1cs._.js +0 -10
- package/.next/server/chunks/_0fzqt2y._.js +0 -100
- package/.next/server/chunks/_0jgm3b8._.js +0 -55
- package/.next/server/chunks/_0ks6_sg._.js +0 -55
- package/.next/server/chunks/_0tzfesa._.js +0 -3
- package/.next/server/chunks/_0zmestz._.js +0 -55
- package/.next/server/chunks/_12nr4xc._.js +0 -3
- package/.next/server/chunks/_1hzrsvg._.js +0 -55
- package/.next/server/chunks/_1uj4_io._.js +0 -10
- package/.next/server/chunks/_1yldgo4._.js +0 -55
- package/.next/server/chunks/features_0scmr4i._.js +0 -3
- package/.next/server/chunks/features_bot_bot_query_ts_12mgkl2._.js +0 -3
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_0ykklj0._.js +0 -3
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1ryg3wh._.js +0 -3
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1vwbnq_._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__01id-v3._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__0b-0i32._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__185grso._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1minz8_._.js +0 -3
- package/.next/server/chunks/ssr/_0j4v8of._.js +0 -3
- package/.next/server/chunks/ssr/_0l81bzy._.js +0 -3
- package/.next/server/chunks/ssr/_10uvw3l._.js +0 -3
- package/.next/server/chunks/ssr/_1jbv7m1._.js +0 -3
- package/.next/server/chunks/ssr/lib_realtime_0aetuyp._.js +0 -24
- package/.next/server/chunks/ssr/lib_realtime_18k_aj-._.js +0 -24
- package/.next/server/chunks/ssr/node_modules_zod_v4_classic_errors_05xv7vp.js +0 -3
- package/.next/static/chunks/0yysv1gzin17t.js +0 -1
- package/.next/static/chunks/1keib_gt066gc.js +0 -1
- package/.next/static/chunks/28g42tw8tsvhd.js +0 -1
- package/.next/static/chunks/2cwjgkt_hoyhj.js +0 -22
- package/.next/static/chunks/2rbf1fpd8n80-.js +0 -22
- package/.next/static/chunks/2ukj8k69y89um.js +0 -1
- package/.next/static/chunks/2wngeetfnzxkp.js +0 -2
- package/.next/static/chunks/388-t2v72jh39.css +0 -1
- package/.next/static/chunks/3fqvc0cg-atq_.js +0 -1
- package/.next/static/chunks/3p4egvfjxpatb.js +0 -1
- package/.next/static/chunks/3qe1w1ei-huhl.js +0 -1
- package/.next/static/chunks/3y40riycdip-i.js +0 -1
- package/.next/static/chunks/45a6zbtkelph9.js +0 -1
- /package/.next/static/{X34BUd9bfdH27ripuwwBm → YR4NWcDDuzwLbTTU7U7Vr}/_buildManifest.js +0 -0
- /package/.next/static/{X34BUd9bfdH27ripuwwBm → YR4NWcDDuzwLbTTU7U7Vr}/_clientMiddlewareManifest.js +0 -0
- /package/.next/static/{X34BUd9bfdH27ripuwwBm → YR4NWcDDuzwLbTTU7U7Vr}/_ssgManifest.js +0 -0
|
@@ -1,15 +1,13 @@
|
|
|
1
|
-
module.exports=[113022,e=>e.a(async(t,o)=>{try{var n=e.i(691296),r=e.i(588762),a=e.i(636608),i=e.i(423620),l=e.i(330436),s=e.i(759118),u=e.i(391830),c=e.i(308070),d=e.i(594537),p=e.i(175885),m=e.i(51083),h=e.i(859727),g=e.i(951056),f=e.i(1363),y=e.i(343229),v=e.i(520401),_=e.i(871096),b=e.i(900533),z=e.i(64774),w=e.i(986507),x=t([s,u,f,v,w]);async function S(t){let{listTaskHistory:o}=await e.A(868649),n=await o({limit:5});if(!n.length)return"No jobs have been handed over yet.";let r=n.map(e=>`"${e.label}" (${e.bot}, ${e.status})`).join(", ");return`There is no job called "${t}". The latest are: ${r}. Call again with one of those names.`}async function k(t){let o=(0,u.createMemoryTools)();if("tidy"===t.target){let{[m.TOOL_NAMES.memory_show]:e,...t}=o;return{...t,[m.TOOL_NAMES.tidy_done]:p.tidyDoneTool}}let x=await (0,_.openWorkspace)();if("thursday"===t.target){var k;let{[m.TOOL_NAMES.memory_show]:s,...u}=o,{crowded:c,heavy:p}=(0,a.tidying)(await (0,f.listNoteIndex)()),_=await (0,v.readCallSkillsOn)()?(0,d.createSkillTools)({sandbox:x,skills:await (0,y.loadSkills)(x)}):{};return{...u,...c||p.length?{[m.TOOL_NAMES.memory_show]:s}:{},..._,...(0,h.createWorkspaceTools)(x,{write:!1}),...(k=t.callId,{[m.TOOL_NAMES.delegate]:(0,n.tool)({description:i.delegateSpec.description,inputSchema:i.delegateSpec.parameters,execute:async({bot:t,request:o,label:n})=>{let{findJobBot:r,listJobBots:a}=await e.A(242792),i=await r(t);if(!i){let e=(await a()).map(e=>e.name);return`There is no bot called "${t}". The bots are: ${e.join(", ")}. Nothing was handed over — call again with one of those.`}let{startTask:l}=await e.A(327784);return{taskId:await l({bot:i.name,request:o,label:n,callId:k}),note:`${i.name} has "${n}". Say so and keep talking — the result is put in front of you later. Everything further about it — an answer, a correction, carrying it on after it reports — is \`${m.TOOL_NAMES.task}\` with "${n}".`}}}),[m.TOOL_NAMES.task]:(0,n.tool)({description:i.taskSpec.description,inputSchema:i.taskSpec.parameters,execute:async({action:t,task:o,answer:n})=>{let{listTaskHistory:a,resolveTask:i}=await e.A(868649);if("status"===t){let e=n?.trim()?{note:"The text in `answer` was not passed on — `status` only reads. Send it again as `answer` if the bot is meant to hear it."}:{};if(o){let t=await i(o);return t?{...e,label:t.label,bot:t.bot,status:t.status,since:(0,r.formatDistanceToNowStrict)((0,b.toDate)(t.updatedAt),{addSuffix:!0}),outcome:t.outcome,..."waiting"===t.status&&t.pending?.options.length?{options:t.pending.options}:{}}:await S(o)}let t=await a({limit:8});return{...e,tasks:t.map(e=>({label:e.label,bot:e.bot,status:e.status,since:(0,r.formatDistanceToNowStrict)((0,b.toDate)(e.updatedAt),{addSuffix:!0}),...e.ask?{asking:e.ask.question,options:e.ask.options}:{},..."running"===e.status?{now:(0,g.taskActivity)(e.lines)}:{},...e.outcome&&"waiting"!==e.status?{outcome:(0,z.clip)(e.outcome,200)}:{}}))}}if(!o)return"Say which job — by its label. Call `status` with no job named to see them.";let l=await i(o);if(!l)return await S(o);let{answerTask:s,cancelTask:u}=await e.A(327784);return"cancel"===t?(await u(l.id),{label:l.label,status:"cancelled"}):n?.trim()?(await s(l.id,n.trim()),{label:l.label,status:"running",note:"running"===l.status?"The bot reads it before its next step.":"The bot picks the job back up from there."}):"Say what to pass on."}})}),...l.CALL_TOOLS}}let I=await (0,y.loadSkills)(x);return{[m.TOOL_NAMES.memory_recall]:o[m.TOOL_NAMES.memory_recall],[m.TOOL_NAMES.memory_remember]:u.botRememberTool,...(0,c.createSearchTool)(await (0,w.resolveSearchModel)(t.model),x),...(0,h.createWorkspaceTools)(x,{write:!0,env:(0,_.jobShellEnv)(t.taskId)}),...await (0,s.createMcpTools)(t.bot,x),...(0,d.createSkillTools)({sandbox:x,skills:I}),[m.TOOL_NAMES.ask_thursday]:i.askThursdayTool,[m.TOOL_NAMES.report]:i.reportTool}}[s,u,f,v,w]=x.then?(await x)():x,e.s(["loadTools",0,k]),o()}catch(e){o(e)}},!1),986507,e=>e.a(async(t,o)=>{try{var n=e.i(128278),r=e.i(19698),a=e.i(970354),i=e.i(853421),l=e.i(296194),s=e.i(736756),u=e.i(656719),c=e.i(724185),d=e.i(938281),p=e.i(212389),m=e.i(64774),h=e.i(864328),g=t([c]);function f(e,t){switch(e.provider){case"openai":{let o=(0,a.createOpenAI)({apiKey:t});return{ref:e,model:o(e.model),searchTools:{search:o.tools.webSearch()}}}case"anthropic":{let o=(0,n.createAnthropic)({apiKey:t});return{ref:e,model:o(e.model),searchTools:{search:o.tools.webSearch_20260209()}}}case"google":{let o=(0,r.createGoogleGenerativeAI)({apiKey:t});return{ref:e,model:o(e.model),searchTools:{search:o.tools.googleSearch({})}}}case"xai":{let o=(0,i.createXai)({apiKey:t});return{ref:e,model:o(e.model),searchTools:{search:o.tools.webSearch()}}}case"vercel-ai-gateway":{let o=(0,s.createGateway)({apiKey:t});return{ref:e,model:o(e.model),searchTools:null}}default:(0,p.publicError)(`Not supported provider: ${String(e.provider)}`)}}[c]=g.then?(await g)():g;let k=null;function y(e){if(null==e||""===e)return null;let t=Number(e);return Number.isFinite(t)?Math.round(1e6*t*1e4)/1e4:null}async function v(){if(k&&Date.now()-k.at<6e5)return k.models;let e=await fetch("https://ai-gateway.vercel.sh/v1/models",{headers:{accept:"application/json"}}).catch(e=>{d.logger.warn({cause:e},"gateway catalog unreachable"),(0,p.publicError)("Could not reach the gateway")});e.ok||(0,p.publicError)(`The gateway answered ${e.status}`);let t=((await e.json()).data??[]).filter(e=>!!e.id).map(e=>{let t;return{id:e.id,label:e.name||e.id,owner:e.owned_by||e.id.slice(0,e.id.indexOf("/")),type:(t=e.type??null)===h.GATEWAY_TEXT&&(e.modalities?.output??[]).includes("image")?"image":t,tags:e.tags??[],price:function(e){let t=e.pricing??{},o=y(t.input),n=y(t.output);if((e.tags??[]).includes("free")||0===o)return{in:0,out:0,note:null,free:!0};let r=t.transcription_duration_cost_per_second??t.realtime_session_duration_cost_per_second;if(r)return{in:null,out:null,note:`$${r}/s`,free:!1};if(t.speech_input_character_cost)return{in:null,out:null,note:"per character",free:!1};let a=Array.isArray(t.video_duration_pricing)?t.video_duration_pricing[0]:null;if(a)return{in:null,out:null,note:`$${a.cost_per_second}/s ${a.resolution}`,free:!1};let i=t.image?`$${t.image}/image`:t.image_dimension_quality_pricing?"per image, by size":null;return null===o&&null===n?{in:null,out:null,note:i,free:!1}:{in:o,out:n,note:t.input_tiers?"tiered":t.varies_by_provider?"varies":i&&"+ per image",free:!1}}(e),retiring:!!e.deprecated_at}}).sort((e,t)=>e.id.localeCompare(t.id));return k={at:Date.now(),models:t},t}async function _(){return await v().then(e=>new Set(e.map(e=>e.id))).catch(()=>null)}async function b(e,t){if("vercel-ai-gateway"!==e)return t;let o=await _();if(!o)return t;let n=t.filter(e=>o.has(e.id));return n.length>0?n:t}async function z(e){let{label:t,apiKeyName:o}=h.TEXT_MODEL_PROVIDERS[e.provider],n=await (0,c.readConfig)(o);return n||(0,p.publicError)(`No ${t} key — add one in Config.`),f(e,n)}async function w(e){let t=async e=>(0,h.defaultModelOf)({suggestModels:await b(e.id,e.suggestModels)}),o=e?h.TEXT_MODEL_PROVIDER_LIST.find(t=>t.id===e):void 0,n=h.SPEACH_MODEL_PROVIDER_LIST.map(e=>({...h.TEXT_MODEL_PROVIDERS[e.id],id:e.id}));if(o){let e=await t(o);if(e)return{provider:o.id,model:e}}let r=(0,h.parseTextModel)(await (0,c.readConfig)(u.DEFAULT_MODEL_KEY)??void 0);if(r&&await (0,c.readConfig)(h.TEXT_MODEL_PROVIDERS[r.provider].apiKeyName))return r;for(let e of[...n,...h.TEXT_MODEL_PROVIDER_LIST]){if(!await (0,c.readConfig)(e.apiKeyName))continue;let o=await t(e);if(o)return d.logger.info(`no model set, falling back to ${e.id}/${o}`),{provider:e.id,model:o}}(0,p.publicError)("No model key is set — add one in Config")}async function x(e){if(e?.searchTools)return e;for(let e of h.TEXT_MODEL_PROVIDER_LIST){let t=await (0,c.readConfig)(e.apiKeyName),o=(0,h.cheapestModelOf)(e);if(!t||!o)continue;let n=f({provider:e.id,model:o},t);if(n.searchTools)return n}return null}async function S(e){let t=(0,h.parseMediaModel)(await (0,c.readConfig)(u.MEDIA_MODEL_KEYS[e]));if(!t||!(0,h.canMakeKind)(t.provider,e))return null;let o=await (0,c.readConfig)(h.MEDIA_MODEL_PROVIDERS[t.provider].apiKeyName);return o?{ref:t,apiKey:o}:null}e.s(["buildImageModel",0,function(e,t){switch(e.provider){case"openai":return(0,a.createOpenAI)({apiKey:t}).image(e.model);case"google":return(0,r.createGoogleGenerativeAI)({apiKey:t}).image(e.model);case"xai":return(0,i.createXai)({apiKey:t}).image(e.model);case"vercel-ai-gateway":return(0,s.createGateway)({apiKey:t}).image(e.model);default:(0,p.publicError)(`Not supported image provider: ${String(e.provider)}`)}},"buildSpeechModel",0,function(e,t){switch(e.provider){case"openai":return(0,a.createOpenAI)({apiKey:t}).speech(e.model);case"google":return(0,r.createGoogleGenerativeAI)({apiKey:t}).speech(e.model);case"xai":return(0,i.createXai)({apiKey:t}).speech();case"vercel-ai-gateway":return(0,s.createGateway)({apiKey:t}).speech(e.model);default:(0,p.publicError)(`Not supported speech provider: ${String(e.provider)}`)}},"buildTranscriptionModel",0,function(e,t){switch(e.provider){case"openai":return(0,a.createOpenAI)({apiKey:t}).transcription(e.model);case"google":return(0,r.createGoogleGenerativeAI)({apiKey:t}).transcription(e.model);case"xai":return(0,i.createXai)({apiKey:t}).transcription();case"vercel-ai-gateway":return(0,s.createGateway)({apiKey:t}).transcription(e.model);default:(0,p.publicError)(`Not supported transcription provider: ${String(e.provider)}`)}},"buildVideoModel",0,function(e,t){switch(e.provider){case"google":return(0,r.createGoogleGenerativeAI)({apiKey:t}).video(e.model);case"xai":return(0,i.createXai)({apiKey:t}).video(e.model);case"vercel-ai-gateway":return(0,s.createGateway)({apiKey:t}).video(e.model);default:(0,p.publicError)(`${e.provider} has no video model`)}},"getTextModel",0,z,"modelErrorToString",0,function(e){if(!l.APICallError.isInstance(e))return(0,m.errorToString)(e);let t=e.statusCode?` (${e.statusCode})`:"",o=e.responseBody?.trim(),n=o&&!o.includes(e.message)?` ${(0,m.clip)(o,300)}`:"";return`${e.message}${t}${n}`},"resolveDefaultModel",0,w,"resolveMediaRef",0,S,"resolveSearchModel",0,x]),o()}catch(e){o(e)}},!1),636608,e=>{"use strict";var t=e.i(489938),o=e.i(333925),n=e.i(232549),r=e.i(900533),a=e.i(610150);function i(e,t=!1){return e.length?e.map(e=>{var o;let n,a=e.aliases?.length?` ${e.aliases.map(e=>`"${e}"`).join(" ")}`:"",i=t?` \xb7 ${o=e.lastSeenAt,(n=Math.floor((Date.now()-(0,r.toDate)(o).getTime())/864e5))>=365?`${Math.floor(n/365)}y`:n>=30?`${Math.floor(n/30)}mo`:`${Math.max(n,0)}d`}`:"";return`- ${e.path} — ${e.description?.trim()} (${e.factCount})${a}${i}`}).join("\n"):"(nothing saved yet)"}e.s(["carriedLines",0,e=>e.map(e=>`- ${e.text} \xb7 ${e.path} #${e.id}`).join("\n"),"mcpToolLines",0,function(e){let t=new Map;for(let o of e){let e=t.get(o.server);e?e.push(o.name):t.set(o.server,[o.name])}return[...t].map(([e,t])=>`- **${e}**: ${t.join(", ")}`).join("\n")},"noteLines",0,i,"nowLine",0,(e=new Date)=>`**Now**: ${(0,t.format)(e,"yyyy-MM-dd (EEE) HH:mm")} ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,"skillLines",0,(e,t={})=>e.map(e=>{var n;let r,a;return`- **${e.name}**: ${t.short?(n=e.description,r=o.PROMPT_LINE.skill,(a=n.trim().split(/(?<=[.。])\s|\n/)[0].trim()).length>r?`${a.slice(0,r).trim()}…`:a):e.description}`}).join("\n"),"tidying",0,e=>({crowded:(0,a.estimateTokens)(i(e))>o.MEMORY_LISTING_TOKENS,heavy:e.filter(e=>e.factCount>n.MANY_FACTS)})])},330436,e=>{"use strict";var t=e.i(691296),o=e.i(749906),n=e.i(51083);let r={name:n.TOOL_NAMES.end_call,description:`End the call.
|
|
1
|
+
module.exports=[113022,e=>e.a(async(t,o)=>{try{var n=e.i(691296),r=e.i(588762),a=e.i(333925),i=e.i(636608),l=e.i(423620),s=e.i(330436),u=e.i(759118),c=e.i(391830),d=e.i(308070),p=e.i(594537),m=e.i(175885),h=e.i(51083),g=e.i(859727),f=e.i(799791),y=e.i(951056),v=e.i(1363),_=e.i(343229),b=e.i(520401),z=e.i(871096),w=e.i(900533),x=e.i(938281),S=e.i(610150),k=e.i(64774),I=e.i(986507),T=t([u,c,f,v,b,I]);async function C(t){let{listTaskHistory:o}=await e.A(868649),n=await o({limit:5});if(!n.length)return"No jobs have been handed over yet.";let r=n.map(e=>`"${e.label}" (${e.bot}, ${e.status})`).join(", ");return`There is no job called "${t}". The latest are: ${r}. Call again with one of those names.`}async function E(e,t){let o=[];for(let[e,r]of Object.entries(t)){let t=await (0,n.asSchema)(r.inputSchema).jsonSchema,a="string"==typeof r.description?r.description:"";o.push({name:e,tokens:(0,S.estimateTokens)(a)+(0,S.estimateTokens)(JSON.stringify(t))})}o.sort((e,t)=>t.tokens-e.tokens);let r=o.reduce((e,t)=>e+t.tokens,0);x.logger.debug(`${e} tools ${r} tokens over ${o.length} — ${o.map(e=>`${e.name} ${e.tokens}`).join(", ")}`)}async function M(e){let t=await j(e);return a.IS_DEV&&await E(e.target,t),t}async function j(t){let o=(0,c.createMemoryTools)("tidy"===t.target?"tidy":"call");if("tidy"===t.target){let{[h.TOOL_NAMES.memory_show]:e,...t}=o;return{...t,[h.TOOL_NAMES.tidy_done]:m.tidyDoneTool}}let a=await (0,z.openWorkspace)();if("thursday"===t.target){var x;let{[h.TOOL_NAMES.memory_show]:u,...c}=o,{crowded:d,heavy:m}=(0,i.tidying)(await (0,v.listNoteIndex)()),f=await (0,b.readCallSkillsOn)()?(0,p.createSkillTools)({sandbox:a,skills:await (0,_.loadSkills)(a)}):{};return{...c,...d||m.length?{[h.TOOL_NAMES.memory_show]:u}:{},...f,...(0,g.createWorkspaceTools)(a,{write:!1}),...(x=t.callId,{[h.TOOL_NAMES.delegate]:(0,n.tool)({description:l.delegateSpec.description,inputSchema:l.delegateSpec.parameters,execute:async({bot:t,request:o,label:n})=>{let{findJobBot:r,listJobBots:a}=await e.A(242792),i=await r(t);if(!i){let e=(await a()).map(e=>e.name);return`There is no bot called "${t}". The bots are: ${e.join(", ")}. Nothing was handed over — call again with one of those.`}let{startTask:l}=await e.A(327784);return{taskId:await l({bot:i.name,request:o,label:n,callId:x}),note:`${i.name} has "${n}". Say so and keep talking — the result is put in front of you later. Everything further about it — an answer, a correction, carrying it on after it reports — is \`${h.TOOL_NAMES.task}\` with "${n}".`}}}),[h.TOOL_NAMES.task]:(0,n.tool)({description:l.taskSpec.description,inputSchema:l.taskSpec.parameters,execute:async({action:t,task:o,answer:n})=>{let{listTaskHistory:a,resolveTask:l}=await e.A(868649);if("status"===t){let e=n?.trim()?{note:"The text in `answer` was not passed on — `status` only reads. Send it again as `answer` if the bot is meant to hear it."}:{},t={now:(0,i.clockNow)()};if(o){let n=await l(o);return n?{...t,...e,label:n.label,bot:n.bot,status:n.status,since:(0,r.formatDistanceToNowStrict)((0,w.toDate)(n.updatedAt),{addSuffix:!0}),outcome:n.outcome,..."waiting"===n.status&&n.pending?.options.length?{options:n.pending.options}:{}}:await C(o)}let s=await a({limit:8});return{...t,...e,tasks:s.map(e=>({label:e.label,bot:e.bot,status:e.status,since:(0,r.formatDistanceToNowStrict)((0,w.toDate)(e.updatedAt),{addSuffix:!0}),...e.ask?{asking:e.ask.question,options:e.ask.options}:{},..."running"===e.status?{now:(0,y.taskActivity)(e.lines)}:{},...e.outcome&&"waiting"!==e.status?{outcome:(0,k.clip)(e.outcome,200)}:{}}))}}if(!o)return"Say which job — by its label. Call `status` with no job named to see them.";let s=await l(o);if(!s)return await C(o);let{answerTask:u,cancelTask:c}=await e.A(327784);return"cancel"===t?(await c(s.id),{label:s.label,status:"cancelled"}):n?.trim()?(await u(s.id,n.trim()),{label:s.label,status:"running",note:"running"===s.status?"The bot reads it before its next step.":"The bot picks the job back up from there."}):"Say what to pass on."}})}),...s.CALL_TOOLS}}let S=await (0,_.loadSkills)(a);return{[h.TOOL_NAMES.memory_recall]:o[h.TOOL_NAMES.memory_recall],[h.TOOL_NAMES.memory_remember]:c.botRememberTool,...(0,d.createSearchTool)(await (0,I.resolveSearchModel)(t.model),a),...(0,g.createWorkspaceTools)(a,{write:!0,env:(0,z.jobShellEnv)(t.taskId),guide:!0}),...await (0,u.createMcpTools)(t.bot,a),...(0,p.createSkillTools)({sandbox:a,skills:S}),[h.TOOL_NAMES.ask_thursday]:l.askThursdayTool,[h.TOOL_NAMES.report]:(0,l.createReportTool)(await (0,f.readBotNotesOn)())}}[u,c,f,v,b,I]=T.then?(await T)():T,e.s(["loadTools",0,M]),o()}catch(e){o(e)}},!1),986507,e=>e.a(async(t,o)=>{try{var n=e.i(128278),r=e.i(19698),a=e.i(970354),i=e.i(853421),l=e.i(296194),s=e.i(736756),u=e.i(656719),c=e.i(724185),d=e.i(938281),p=e.i(212389),m=e.i(64774),h=e.i(864328),g=t([c]);function f(e,t){switch(e.provider){case"openai":{let o=(0,a.createOpenAI)({apiKey:t});return{ref:e,model:o(e.model),searchTools:{search:o.tools.webSearch()}}}case"anthropic":{let o=(0,n.createAnthropic)({apiKey:t});return{ref:e,model:o(e.model),searchTools:{search:o.tools.webSearch_20260209()}}}case"google":{let o=(0,r.createGoogleGenerativeAI)({apiKey:t});return{ref:e,model:o(e.model),searchTools:{search:o.tools.googleSearch({})}}}case"xai":{let o=(0,i.createXai)({apiKey:t});return{ref:e,model:o(e.model),searchTools:{search:o.tools.webSearch()}}}case"vercel-ai-gateway":{let o=(0,s.createGateway)({apiKey:t});return{ref:e,model:o(e.model),searchTools:null}}default:(0,p.publicError)(`Not supported provider: ${String(e.provider)}`)}}[c]=g.then?(await g)():g;let k=null;function y(e){if(null==e||""===e)return null;let t=Number(e);return Number.isFinite(t)?Math.round(1e6*t*1e4)/1e4:null}async function v(){if(k&&Date.now()-k.at<6e5)return k.models;let e=await fetch("https://ai-gateway.vercel.sh/v1/models",{headers:{accept:"application/json"}}).catch(e=>{d.logger.warn({cause:e},"gateway catalog unreachable"),(0,p.publicError)("Could not reach the gateway")});e.ok||(0,p.publicError)(`The gateway answered ${e.status}`);let t=((await e.json()).data??[]).filter(e=>!!e.id).map(e=>{let t;return{id:e.id,label:e.name||e.id,owner:e.owned_by||e.id.slice(0,e.id.indexOf("/")),type:(t=e.type??null)===h.GATEWAY_TEXT&&(e.modalities?.output??[]).includes("image")?"image":t,tags:e.tags??[],price:function(e){let t=e.pricing??{},o=y(t.input),n=y(t.output);if((e.tags??[]).includes("free")||0===o)return{in:0,out:0,note:null,free:!0};let r=t.transcription_duration_cost_per_second??t.realtime_session_duration_cost_per_second;if(r)return{in:null,out:null,note:`$${r}/s`,free:!1};if(t.speech_input_character_cost)return{in:null,out:null,note:"per character",free:!1};let a=Array.isArray(t.video_duration_pricing)?t.video_duration_pricing[0]:null;if(a)return{in:null,out:null,note:`$${a.cost_per_second}/s ${a.resolution}`,free:!1};let i=t.image?`$${t.image}/image`:t.image_dimension_quality_pricing?"per image, by size":null;return null===o&&null===n?{in:null,out:null,note:i,free:!1}:{in:o,out:n,note:t.input_tiers?"tiered":t.varies_by_provider?"varies":i&&"+ per image",free:!1}}(e),retiring:!!e.deprecated_at}}).sort((e,t)=>e.id.localeCompare(t.id));return k={at:Date.now(),models:t},t}async function _(){return await v().then(e=>new Set(e.map(e=>e.id))).catch(()=>null)}async function b(e,t){if("vercel-ai-gateway"!==e)return t;let o=await _();if(!o)return t;let n=t.filter(e=>o.has(e.id));return n.length>0?n:t}async function z(e){let{label:t,apiKeyName:o}=h.TEXT_MODEL_PROVIDERS[e.provider],n=await (0,c.readConfig)(o);return n||(0,p.publicError)(`No ${t} key — add one in Config.`),f(e,n)}async function w(e){let t=async e=>(0,h.defaultModelOf)({suggestModels:await b(e.id,e.suggestModels)}),o=e?h.TEXT_MODEL_PROVIDER_LIST.find(t=>t.id===e):void 0,n=h.SPEACH_MODEL_PROVIDER_LIST.map(e=>({...h.TEXT_MODEL_PROVIDERS[e.id],id:e.id}));if(o){let e=await t(o);if(e)return{provider:o.id,model:e}}let r=(0,h.parseTextModel)(await (0,c.readConfig)(u.DEFAULT_MODEL_KEY)??void 0);if(r&&await (0,c.readConfig)(h.TEXT_MODEL_PROVIDERS[r.provider].apiKeyName))return r;for(let e of[...n,...h.TEXT_MODEL_PROVIDER_LIST]){if(!await (0,c.readConfig)(e.apiKeyName))continue;let o=await t(e);if(o)return d.logger.info(`no model set, falling back to ${e.id}/${o}`),{provider:e.id,model:o}}(0,p.publicError)("No model key is set — add one in Config")}async function x(e){if(e?.searchTools)return e;for(let e of h.TEXT_MODEL_PROVIDER_LIST){let t=await (0,c.readConfig)(e.apiKeyName),o=(0,h.cheapestModelOf)(e);if(!t||!o)continue;let n=f({provider:e.id,model:o},t);if(n.searchTools)return n}return null}async function S(e){let t=(0,h.parseMediaModel)(await (0,c.readConfig)(u.MEDIA_MODEL_KEYS[e]));if(!t||!(0,h.canMakeKind)(t.provider,e))return null;let o=await (0,c.readConfig)(h.MEDIA_MODEL_PROVIDERS[t.provider].apiKeyName);return o?{ref:t,apiKey:o}:null}e.s(["buildImageModel",0,function(e,t){switch(e.provider){case"openai":return(0,a.createOpenAI)({apiKey:t}).image(e.model);case"google":return(0,r.createGoogleGenerativeAI)({apiKey:t}).image(e.model);case"xai":return(0,i.createXai)({apiKey:t}).image(e.model);case"vercel-ai-gateway":return(0,s.createGateway)({apiKey:t}).image(e.model);default:(0,p.publicError)(`Not supported image provider: ${String(e.provider)}`)}},"buildSpeechModel",0,function(e,t){switch(e.provider){case"openai":return(0,a.createOpenAI)({apiKey:t}).speech(e.model);case"google":return(0,r.createGoogleGenerativeAI)({apiKey:t}).speech(e.model);case"xai":return(0,i.createXai)({apiKey:t}).speech();case"vercel-ai-gateway":return(0,s.createGateway)({apiKey:t}).speech(e.model);default:(0,p.publicError)(`Not supported speech provider: ${String(e.provider)}`)}},"buildTranscriptionModel",0,function(e,t){switch(e.provider){case"openai":return(0,a.createOpenAI)({apiKey:t}).transcription(e.model);case"google":return(0,r.createGoogleGenerativeAI)({apiKey:t}).transcription(e.model);case"xai":return(0,i.createXai)({apiKey:t}).transcription();case"vercel-ai-gateway":return(0,s.createGateway)({apiKey:t}).transcription(e.model);default:(0,p.publicError)(`Not supported transcription provider: ${String(e.provider)}`)}},"buildVideoModel",0,function(e,t){switch(e.provider){case"google":return(0,r.createGoogleGenerativeAI)({apiKey:t}).video(e.model);case"xai":return(0,i.createXai)({apiKey:t}).video(e.model);case"vercel-ai-gateway":return(0,s.createGateway)({apiKey:t}).video(e.model);default:(0,p.publicError)(`${e.provider} has no video model`)}},"getTextModel",0,z,"modelErrorToString",0,function(e){if(!l.APICallError.isInstance(e))return(0,m.errorToString)(e);let t=e.statusCode?` (${e.statusCode})`:"",o=e.responseBody?.trim(),n=o&&!o.includes(e.message)?` ${(0,m.clip)(o,300)}`:"";return`${e.message}${t}${n}`},"resolveDefaultModel",0,w,"resolveMediaRef",0,S,"resolveSearchModel",0,x]),o()}catch(e){o(e)}},!1),636608,e=>{"use strict";var t=e.i(489938),o=e.i(333925),n=e.i(232549),r=e.i(900533),a=e.i(938281),i=e.i(610150);let l=(e=new Date)=>`${(0,t.format)(e,"yyyy-MM-dd (EEE) HH:mm")} ${Intl.DateTimeFormat().resolvedOptions().timeZone}`;function s(e,t=!1){return e.length?e.map(e=>{var o;let n,a=e.aliases?.length?` ${e.aliases.map(e=>`"${e}"`).join(" ")}`:"",i=t?` \xb7 ${o=e.lastSeenAt,(n=Math.floor((Date.now()-(0,r.toDate)(o).getTime())/864e5))>=365?`${Math.floor(n/365)}y`:n>=30?`${Math.floor(n/30)}mo`:`${Math.max(n,0)}d`}`:"";return`- ${e.path} — ${e.description?.trim()} (${e.factCount})${a}${i}`}).join("\n"):"(nothing saved yet)"}e.s(["carriedLines",0,e=>e.map(e=>`- ${e.text} \xb7 ${e.path} #${e.id}`).join("\n"),"clockNow",0,l,"logPromptSize",0,function(e,t){let n=(0,i.sectionTokens)(t),r=n.reduce((e,t)=>e+t.tokens,0);a.logger.debug(`${e} prompt ${r} tokens — ${n.map(e=>`${e.name} ${e.tokens}`).join(", ")}`);let l=n[0];r>o.PROMPT_BUDGET&&l&&a.logger.warn(`${e} prompt is ${r} tokens, over ${o.PROMPT_BUDGET}: ${l.name} carries ${l.tokens} of it. Every call and every job pays this.`)},"mcpToolLines",0,function(e){let t=new Map;for(let o of e){let e=t.get(o.server);e?e.push(o.name):t.set(o.server,[o.name])}return[...t].map(([e,t])=>`- **${e}**: ${t.join(", ")}`).join("\n")},"noteLines",0,s,"nowLine",0,(e=new Date)=>`**Now**: ${l(e)}`,"skillLines",0,(e,t={})=>e.map(e=>{var n;let r,a;return`- **${e.name}**: ${t.short?(n=e.description,r=o.PROMPT_LINE.skill,(a=n.trim().split(/(?<=[.。])\s|\n/)[0].trim()).length>r?`${a.slice(0,r).trim()}…`:a):e.description}`}).join("\n"),"tidying",0,e=>({crowded:(0,i.estimateTokens)(s(e))>o.MEMORY_LISTING_TOKENS,heavy:e.filter(e=>e.factCount>n.MANY_FACTS)})])},330436,e=>{"use strict";var t=e.i(691296),o=e.i(749906),n=e.i(51083);let r={name:n.TOOL_NAMES.end_call,description:`End the call.
|
|
2
2
|
|
|
3
|
-
Say goodbye first — nothing said after this reaches the user.`,parameters:o.object({})},a=(0,t.tool)({description:r.description,inputSchema:r.parameters}),i={[n.TOOL_NAMES.end_call]:a};e.s(["CALL_TOOLS",0,i])},759118,e=>e.a(async(t,o)=>{try{var n=e.i(691296),r=e.i(749906),a=e.i(51083),i=e.i(993195),l=e.i(340697),s=t([i,l]);[i,l]=s.then?(await s)():s;let d={[a.TOOL_NAMES.tool_search]:{name:a.TOOL_NAMES.tool_search,description:`
|
|
4
|
-
|
|
5
|
-
The Connected tools section names every server and every tool on it, and that is all it names: there is no description and no parameter schema, so a tool cannot be invoked from that list alone. Name a server and the tools on it, and this returns each one's description and its exact inputSchema. Then run one with \`${a.TOOL_NAMES.tool_call}\`.`,parameters:r.object({server:r.string().describe("A server name, exactly as the Connected tools section writes it."),tools:r.string().array().describe("Tool names listed under that server. Only the ones you may actually call — schemas are large, and at most 8 come back.")})},[a.TOOL_NAMES.tool_call]:{name:a.TOOL_NAMES.tool_call,description:`Run one tool whose definition came back from \`${a.TOOL_NAMES.tool_search}\`.`,parameters:r.object({server:r.string().describe("The server the tool lives on."),tool:r.string().describe("Its name, as search returned it."),args:r.record(r.string(),r.unknown()).nullable().describe("Arguments matching the inputSchema search returned — do not guess. Null when it takes none."),description:r.string().nullable().describe("One short line for the user: what this call is for. Shown on their screen while it runs.")})}},p=(e,t)=>`${e.replace(/[^a-zA-Z0-9]+/g,"_")}__${t.replace(/[^a-zA-Z0-9_-]+/g,"_")}`.slice(0,64);async function u(e,t){let[o,r]=await Promise.all([(0,l.listConnectedToolNames)(),(0,i.findPinnedTools)(e)]),a={};for(let e of r){let o=p(e.server,e.name);a[o]||(a[o]=(0,n.tool)({description:e.description??`${e.name} on the ${e.server} server.`,inputSchema:(0,n.jsonSchema)(e.inputSchema??{type:"object",properties:{}}),execute:(o,{abortSignal:n})=>(0,l.callConnectedTool)(t,e.server,e.name,o??void 0,n)}))}return o.length>r.length&&Object.assign(a,m(t)),a}async function c(e){let t=(await (0,l.listConnectedToolNames)(e)).map(e=>e.name);if(t.length)return`Tools on "${e}": ${t.join(", ")}.`;let o=await (0,l.listConnectedServerNames)();return o.length?`There is no server called "${e}". Connected: ${o.join(", ")}.`:"Nothing is connected."}let m=e=>({[a.TOOL_NAMES.tool_search]:(0,n.tool)({description:d[a.TOOL_NAMES.tool_search].description,inputSchema:d[a.TOOL_NAMES.tool_search].parameters,execute:async({server:e,tools:t})=>{let o=[...new Set(t.map(e=>e.trim()).filter(Boolean))],n=o.slice(0,8),r=await (0,l.findConnectedSchemas)(e.trim(),n);if(!r.length)return{tools:[],note:await c(e)};let a=n.filter(e=>!r.some(t=>t.name===e)),i=o.slice(8),s=[a.length?`Not on "${e}": ${a.join(", ")}.`:"",i.length?`Only 8 at a time — ask again for: ${i.join(", ")}.`:""].filter(Boolean);return{tools:r,...s.length?{note:s.join(" ")}:{}}}}),[a.TOOL_NAMES.tool_call]:(0,n.tool)({description:d[a.TOOL_NAMES.tool_call].description,inputSchema:d[a.TOOL_NAMES.tool_call].parameters,execute:async({server:t,tool:o,args:n},{abortSignal:r})=>(await (0,l.listConnectedToolNames)(t.trim())).some(e=>e.name===o.trim())?(0,l.callConnectedTool)(e,t.trim(),o.trim(),n??void 0,r):{status:"error",text:await c(t)}})});e.s(["createMcpTools",0,u]),o()}catch(e){o(e)}},!1),391830,e=>e.a(async(t,o)=>{try{var n=e.i(691296),r=e.i(749906),a=e.i(232347),i=e.i(51083),l=e.i(1363),s=e.i(232549),u=t([l]);[l]=u.then?(await u)():u;let c="Deleted for good. The listing in your instructions is from when this session opened and still shows it that way until the next one.",d=(0,n.tool)({description:"Save a lasting fact about the user. Only for what outlives this job; what the job itself turned up goes in the report.",inputSchema:r.object({path:r.string().describe("Exactly as the listing writes it, or a new path following the same convention."),facts:r.string().array().describe("One statement each, standing on its own later.")}),execute:async({path:e,facts:t})=>{let o=e.trim(),n=t.map(e=>e.trim()).filter(Boolean);if(!n.length)return{note:"Nothing to write: send a fact."};let r=await (0,l.resolveNotePath)(o),a=r||(0,s.isMemoryPath)(o)?r??o:s.MEMORY_INBOX;return await (0,l.writeNotes)([{path:a,facts:n.map(e=>({text:e}))}]),{note:a===o?`Saved to ${a}.`:`Saved to ${a}: "${o}" is not a path this listing can carry.`}}});e.s(["botRememberTool",0,d,"createMemoryTools",0,()=>({[i.TOOL_NAMES.memory_recall]:(0,n.tool)({description:"Open one note from the listing, whole.",inputSchema:r.object({path:r.string().describe("Exactly as the listing writes it — the path, or one of the names in quotes after it.")}),execute:async({path:e})=>{let t,o,{notes:n}=await (0,l.readNotes)([e]),r=n[0];return r?r.facts.length>s.MANY_FACTS?{...r,note:(t=r.path,o=r.facts.length,` ${t} carries ${o} facts — enough that it is worth tidying. Put it on screen with \`${i.TOOL_NAMES.memory_show}\` and ask which of it they no longer need.`).trim()}:r:{note:`Nothing on the listing called ${e.trim()}.`}}}),[i.TOOL_NAMES.memory_remember]:(0,n.tool)({description:"Write to one note: facts, and the line the listing shows for it. The path is the key — a path not on the listing is created (with at least one fact), one that is gets amended.",inputSchema:r.object({path:r.string().describe("Exactly as the listing writes it, or a new path following the same convention."),facts:r.object({text:r.string().describe("One statement that stands on its own later."),replaces:r.number().int().nullable().describe("The id of the fact this replaces — from this note as handed back here or by `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."),alwaysLoad:r.boolean().nullable().describe(`True carries this line into every call's instructions without opening its note — for what to call them, their language and register, a standing rule. At most ${s.ALWAYS_LOADED_MAX}. Null leaves it; false makes a carried line an ordinary fact.`)}).array().nullable().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. Null when only naming it."),description:r.string().nullable().describe(`One line saying what this note is about, not what it currently says. Give it for a new note, or when the line no longer fits. Null leaves it; ${s.MEMORY_ALWAYS_LISTED.join(" and ")} keep their own line.`),aliases:r.string().array().nullable().describe('What the user calls this note out loud, in the language they say it — the words they would use to ask for it, not the facts inside. A note at people/yuri might be "Yuri" and "my wife". Replaces the set it has, so send the whole set. Null leaves it.')}),execute:async e=>{let t=e.path.trim(),o=await (0,l.resolveNotePath)(t),n=e.aliases??null,r=(0,s.isAlwaysListed)(o??t)?null:e.description?.trim()||null,a=e.facts??[];if(!a.length&&!r&&!n)return{note:"Nothing to write: send facts, a line, names, or any of them."};if(!o&&!a.length)return{note:`Nothing on the listing called ${t}. A note comes into being with a fact — send at least one.`};let i=o||(0,s.isMemoryPath)(t)?{path:o??t,description:r,aliases:n,facts:a}:{path:s.MEMORY_INBOX,description:"Facts with nowhere obvious to go",facts:a},u=await (0,l.writeNotes)([i]),c=i.path!==t?` Filed under ${i.path}: "${t}" is not a path this listing can carry. If that is not where it belongs, write it again under one that is.`:"",d=u.unnamed.length?` ${u.unnamed[0]} is new and has no line yet — the listing shows its first fact instead. Call again with \`description\` (one line about what it is) and \`aliases\` (the names they say for it).`:"",p=u.notLoaded.length?` All ${s.ALWAYS_LOADED_MAX} carried lines are taken, so ${u.notLoaded.map(e=>`"${e}"`).join(", ")} saved as an ordinary fact. Say which carried line you would drop for it and let them choose.`:"";return{...u.notes[0],note:`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.${c}${d}${p}`}}}),[i.TOOL_NAMES.memory_show]:(0,n.tool)({description:`Put a note on the user's screen so they can see it while you
|
|
3
|
+
Say goodbye first — nothing said after this reaches the user.`,parameters:o.object({})},a=(0,t.tool)({description:r.description,inputSchema:r.parameters}),i={[n.TOOL_NAMES.end_call]:a};e.s(["CALL_TOOLS",0,i])},759118,e=>e.a(async(t,o)=>{try{var n=e.i(691296),r=e.i(749906),a=e.i(51083),i=e.i(993195),l=e.i(340697),s=t([i,l]);[i,l]=s.then?(await s)():s;let d={[a.TOOL_NAMES.tool_search]:{name:a.TOOL_NAMES.tool_search,description:`Return the description and exact inputSchema of tools on a connected server, so they can be called with \`${a.TOOL_NAMES.tool_call}\`.`,parameters:r.object({server:r.string().describe("A server name, exactly as the Connected tools section writes it."),tools:r.string().array().describe("Tool names listed under that server. Only the ones you may actually call — schemas are large, and at most 8 come back.")})},[a.TOOL_NAMES.tool_call]:{name:a.TOOL_NAMES.tool_call,description:`Run one tool whose definition came back from \`${a.TOOL_NAMES.tool_search}\`.`,parameters:r.object({server:r.string().describe("The server the tool lives on."),tool:r.string().describe("Its name, as search returned it."),args:r.record(r.string(),r.unknown()).nullish().describe("Arguments matching the inputSchema search returned — do not guess. Null when it takes none."),description:r.string().nullish().describe("One short line for the user: what this call is for. Shown on their screen while it runs.")})}},p=(e,t)=>`${e.replace(/[^a-zA-Z0-9]+/g,"_")}__${t.replace(/[^a-zA-Z0-9_-]+/g,"_")}`.slice(0,64);async function u(e,t){let[o,r]=await Promise.all([(0,l.listConnectedToolNames)(),(0,i.findPinnedTools)(e)]),a={};for(let e of r){let o=p(e.server,e.name);a[o]||(a[o]=(0,n.tool)({description:e.description??`${e.name} on the ${e.server} server.`,inputSchema:(0,n.jsonSchema)(e.inputSchema??{type:"object",properties:{}}),execute:(o,{abortSignal:n})=>(0,l.callConnectedTool)(t,e.server,e.name,o??void 0,n)}))}return o.length>r.length&&Object.assign(a,m(t)),a}async function c(e){let t=(await (0,l.listConnectedToolNames)(e)).map(e=>e.name);if(t.length)return`Tools on "${e}": ${t.join(", ")}.`;let o=await (0,l.listConnectedServerNames)();return o.length?`There is no server called "${e}". Connected: ${o.join(", ")}.`:"Nothing is connected."}let m=e=>({[a.TOOL_NAMES.tool_search]:(0,n.tool)({description:d[a.TOOL_NAMES.tool_search].description,inputSchema:d[a.TOOL_NAMES.tool_search].parameters,execute:async({server:e,tools:t})=>{let o=[...new Set(t.map(e=>e.trim()).filter(Boolean))],n=o.slice(0,8),r=await (0,l.findConnectedSchemas)(e.trim(),n);if(!r.length)return{tools:[],note:await c(e)};let a=n.filter(e=>!r.some(t=>t.name===e)),i=o.slice(8),s=[a.length?`Not on "${e}": ${a.join(", ")}.`:"",i.length?`Only 8 at a time — ask again for: ${i.join(", ")}.`:""].filter(Boolean);return{tools:r,...s.length?{note:s.join(" ")}:{}}}}),[a.TOOL_NAMES.tool_call]:(0,n.tool)({description:d[a.TOOL_NAMES.tool_call].description,inputSchema:d[a.TOOL_NAMES.tool_call].parameters,execute:async({server:t,tool:o,args:n},{abortSignal:r})=>(await (0,l.listConnectedToolNames)(t.trim())).some(e=>e.name===o.trim())?(0,l.callConnectedTool)(e,t.trim(),o.trim(),n??void 0,r):{status:"error",text:await c(t)}})});e.s(["createMcpTools",0,u]),o()}catch(e){o(e)}},!1),391830,e=>e.a(async(t,o)=>{try{var n=e.i(691296),r=e.i(749906),a=e.i(232347),i=e.i(51083),l=e.i(1363),s=e.i(232549),u=t([l]);[l]=u.then?(await u)():u;let c="Deleted for good. The listing in your instructions is from when this session opened and still shows it that way until the next one.",d=(0,n.tool)({description:"Save a lasting fact about the user. Only for what outlives this job; what the job itself turned up goes in the report.",inputSchema:r.object({path:r.string().describe("Exactly as the listing writes it, or a new path following the same convention."),facts:r.string().array().describe("One statement each, standing on its own later.")}),execute:async({path:e,facts:t})=>{let o=e.trim(),n=t.map(e=>e.trim()).filter(Boolean);if(!n.length)return{note:"Nothing to write: send a fact."};let r=await (0,l.resolveNotePath)(o),a=r||(0,s.isMemoryPath)(o)?r??o:s.MEMORY_INBOX;return await (0,l.writeNotes)([{path:a,facts:n.map(e=>({text:e}))}],"bot"),{note:a===o?`Saved to ${a}.`:`Saved to ${a}: "${o}" is not a path this listing can carry.`}}});e.s(["botRememberTool",0,d,"createMemoryTools",0,e=>({[i.TOOL_NAMES.memory_recall]:(0,n.tool)({description:"Open one note from the listing, whole.",inputSchema:r.object({path:r.string().describe("Exactly as the listing writes it — the path, or one of the names in quotes after it.")}),execute:async({path:e})=>{let t,o,{notes:n}=await (0,l.readNotes)([e]),r=n[0];return r?r.facts.length>s.MANY_FACTS?{...r,note:(t=r.path,o=r.facts.length,` ${t} carries ${o} facts — enough that it is worth tidying. Put it on screen with \`${i.TOOL_NAMES.memory_show}\` and ask which of it they no longer need.`).trim()}:r:{note:`Nothing on the listing called ${e.trim()}.`}}}),[i.TOOL_NAMES.memory_remember]:(0,n.tool)({description:"Write to one note: facts, and the line the listing shows for it. The path is the key — a path not on the listing is created (with at least one fact), one that is gets amended.",inputSchema:r.object({path:r.string().describe("Exactly as the listing writes it, or a new path following the same convention."),facts:r.object({text:r.string().describe("One statement that stands on its own later."),replaces:r.number().int().nullish().describe("The id of the fact this replaces — from this note as handed back here or by `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."),alwaysLoad:r.boolean().nullish().describe(`True carries this line into every call's instructions without opening its note — for what to call them, their language and register, a standing rule. At most ${s.ALWAYS_LOADED_MAX}. Null leaves it; false makes a carried line an ordinary fact.`)}).array().nullish().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. Null when only naming it."),description:r.string().nullish().describe(`One line saying what this note is about, not what it currently says. Give it for a new note, or when the line no longer fits. Null leaves it; ${s.MEMORY_ALWAYS_LISTED.join(" and ")} keep their own line.`),aliases:r.string().array().nullish().describe('What the user calls this note out loud, in the language they say it — the words they would use to ask for it, not the facts inside. A note at people/yuri might be "Yuri" and "my wife". Replaces the set it has, so send the whole set. Null leaves it.')}),execute:async t=>{let o=t.path.trim(),n=await (0,l.resolveNotePath)(o),r=t.aliases??null,a=(0,s.isAlwaysListed)(n??o)?null:t.description?.trim()||null,i=t.facts??[];if(!i.length&&!a&&!r)return{note:"Nothing to write: send facts, a line, names, or any of them."};if(!n&&!i.length)return{note:`Nothing on the listing called ${o}. A note comes into being with a fact — send at least one.`};let u=n||(0,s.isMemoryPath)(o)?{path:n??o,description:a,aliases:r,facts:i}:{path:s.MEMORY_INBOX,description:"Facts with nowhere obvious to go",facts:i},c=await (0,l.writeNotes)([u],e),d=u.path!==o?` Filed under ${u.path}: "${o}" is not a path this listing can carry. If that is not where it belongs, write it again under one that is.`:"",p=c.unnamed.length?` ${c.unnamed[0]} is new and has no line yet — the listing shows its first fact instead. Call again with \`description\` (one line about what it is) and \`aliases\` (the names they say for it).`:"",m=c.notLoaded.length?` All ${s.ALWAYS_LOADED_MAX} carried lines are taken, so ${c.notLoaded.map(e=>`"${e}"`).join(", ")} saved as an ordinary fact. Say which carried line you would drop for it and let them choose.`:"";return{...c.notes[0],note:`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.${d}${p}${m}`}}}),[i.TOOL_NAMES.memory_show]:(0,n.tool)({description:`Put a note on the user's screen so they can see it while you
|
|
6
4
|
talk about it, and take it away again. They cannot edit it there — they say
|
|
7
5
|
what to drop and you drop it.`,inputSchema:r.object({path:r.string().nullable().describe("The note to put on screen, exactly as the listing writes it. Null takes it away.")}),execute:async({path:e})=>{if(!e?.trim())return a.appEvents.emit({type:"memory-view",path:null}),{note:"Taken off the screen."};let{notes:t}=await (0,l.readNotes)([e],{touch:!1}),o=t[0];return o?(a.appEvents.emit({type:"memory-view",path:o.path}),{...o,note:"It is on their screen now, in this order. Ask what they no longer need, and forget only what they name."}):{note:`Nothing on the listing called ${e.trim()}.`}}}),[i.TOOL_NAMES.memory_forget]:(0,n.tool)({description:"Delete one fact for good.",inputSchema:r.object({factId:r.number().int().describe("The id that came with the fact when the note was opened.")}),execute:async({factId:e})=>{let t=await (0,l.forgetFactById)(e);if(!t)return{note:`No fact with id ${e}. Nothing was deleted.`};if(t.noteGone)return{note:`${c} That was the last fact under ${t.path}, so the note went with it.`};let{notes:o}=await (0,l.readNotes)([t.path],{touch:!1});return{...o[0],note:c}}})})]),o()}catch(e){o(e)}},!1),308070,e=>{"use strict";var t=e.i(734732),o=e.i(691296),n=e.i(517435),r=e.i(51083);let a=`Answer the question from the web. Lead with the answer, then
|
|
8
6
|
what supports it. Say plainly what you could not find or confirm — do not fill
|
|
9
7
|
the gap with a guess. Every number carries the date you saw it. Be brief: this
|
|
10
8
|
is read by another model, not by a person.`;e.s(["createSearchTool",0,(e,i)=>{if(!e?.searchTools)return{};let{model:l,searchTools:s}=e;return{[r.TOOL_NAMES.web_search]:(0,o.tool)({description:"Search the web and get back an answer with its sources. For a fact, a price, a date, what a page says. Not for a page that has to be clicked, filled, or signed into — that is the browser.",inputSchema:n.default.object({query:n.default.string().describe("What you want to know, as one full question. Put the place and the time in when they matter — the searcher sees nothing but this line.")}),execute:async({query:e},{abortSignal:o})=>{let{text:n,sources:r}=await (0,t.generateText)({model:l,tools:s,system:a,prompt:e,abortSignal:o}),u=[...new Set(r.flatMap(e=>"url"===e.sourceType?[e.title?`${e.title} — ${e.url}`:e.url]:[]))].slice(0,8);return i.fold([n.trim(),u.length?`Sources:
|
|
11
9
|
${u.join("\n")}`:""].filter(Boolean).join("\n\n"),"web-search")}})}}])},594537,e=>{"use strict";var t=e.i(691296),o=e.i(517435),n=e.i(51083),r=e.i(202837);e.s(["createSkillTools",0,({skills:e,sandbox:a})=>{let i=new Set;return{[n.TOOL_NAMES.load_skill]:(0,t.tool)({description:"Load one skill: its instructions, and the files that ship with it.",inputSchema:o.default.object({name:o.default.string().describe("Exact name from the Skills list. Do not guess names that are not on it.")}),execute:async({name:t})=>{let o=e.find(e=>e.name.toLowerCase()===t.toLowerCase());if(!o)return{error:`No skill named '${t}'.`,available:e.map(e=>e.name)};let n=`${o.path}/SKILL.md`;if(i.has(o.path))return{skillDirectory:o.path,note:`You already loaded '${o.name}' in this run — its instructions are above, unchanged. Scroll back to that result rather than reading it again; if you need the file itself, read ${n} with the shell.`};let l=await a.readFile(n,"utf-8"),{body:s}=(0,r.splitFrontmatter)(l),u=await a.glob("**/*",{path:o.path,limit:50});return i.add(o.path),{skillDirectory:o.path,files:u,content:s}}})}}])},175885,e=>{"use strict";var t=e.i(691296),o=e.i(749906);let n={name:e.i(51083).TOOL_NAMES.tidy_done,description:"Finish. Calling this ends the read — nothing after it runs.",parameters:o.object({summary:o.string().describe("One or two lines on what changed and why, or that nothing needed to.")})},r=(0,t.tool)({description:n.description,inputSchema:n.parameters,execute:async({summary:e})=>({ok:!0,summary:e})});e.s(["tidyDoneTool",0,r])},437905,e=>e.a(async(t,o)=>{try{var n=e.i(912714),r=e.i(750227),a=e.i(734732),i=e.i(489938),l=e.i(517435),s=e.i(333925),u=e.i(986507),c=e.i(51083),d=e.i(938281),p=e.i(64774),m=t([u]);function h(e){return{...e,execute:(t,o)=>{let n=e.inputSchema.safeParse(t);if(!n.success)throw Error(l.default.prettifyError(n.error));return e.execute(n.data,o)}}}[u]=m.then?(await m)():m;let _={images:`${s.PATHS.artifacts}/images`,audio:`${s.PATHS.artifacts}/audio`,transcripts:`${s.PATHS.artifacts}/transcripts`,videos:`${s.PATHS.artifacts}/videos`};function g(e,t){let o=e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,40),n=(0,i.format)(new Date,"yyyyMMdd-HHmmss");return`${n}${o?`-${o}`:""}.${t}`}async function f(e,t,o,n){let r=`${t}/${o}`;return await e.exec(`mkdir -p ${t}`),await e.writeFile(r,Buffer.from(n)),r}let b=e=>`${e}
|
|
12
|
-
Saved. Give the user this path — the file opens from the task row. Do not describe it back to them; they can open it.`,z=(e,t)=>e?.split("/")[1]?.split(";")[0]||t,w=["1:1","16:9","9:16","4:3","3:4"],x=async()=>{let e=await (0,u.resolveMediaRef)("image");if(!e)return null;let t=(0,u.buildImageModel)(e.ref,e.apiKey);return h({name:c.STUDIO_TOOLS.generate_image,description:"Draw an image and save it as a file in the workspace. What comes back is its path.",inputSchema:l.default.object({prompt:l.default.string().describe("What to draw, described: subject, style, mood, what is in frame. The image model does not see the job or the conversation, so nothing can be left implied."),aspectRatio:l.default.enum(w).
|
|
10
|
+
Saved. Give the user this path — the file opens from the task row. Do not describe it back to them; they can open it.`,z=(e,t)=>e?.split("/")[1]?.split(";")[0]||t,w=["1:1","16:9","9:16","4:3","3:4"],x=async()=>{let e=await (0,u.resolveMediaRef)("image");if(!e)return null;let t=(0,u.buildImageModel)(e.ref,e.apiKey);return h({name:c.STUDIO_TOOLS.generate_image,description:"Draw an image and save it as a file in the workspace. What comes back is its path.",inputSchema:l.default.object({prompt:l.default.string().describe("What to draw, described: subject, style, mood, what is in frame. The image model does not see the job or the conversation, so nothing can be left implied."),aspectRatio:l.default.enum(w).nullish().describe("Aspect ratio. Null for square.")}),execute:async({prompt:e,aspectRatio:o},{sandbox:n,abortSignal:r})=>{let{image:i}=await (0,a.generateImage)({model:t,prompt:e,aspectRatio:o??"1:1",abortSignal:r}),l=await f(n,_.images,g(e,z(i.mediaType,"png")),i.uint8Array);return b(l)}})},S=async()=>{let e=await (0,u.resolveMediaRef)("speech");if(!e)return null;let t=(0,u.buildSpeechModel)(e.ref,e.apiKey);return h({name:c.STUDIO_TOOLS.generate_speech,description:"Read text aloud into an audio file in the workspace — something the user listens to or sends, not Thursday's voice. What comes back is its path.",inputSchema:l.default.object({text:l.default.string().min(1).max(4e3).describe("The words to read, up to 4000 characters. Longer pieces are read in parts, one call each."),voice:l.default.string().nullish().describe("A voice name the provider knows. Null for its default."),instructions:l.default.string().nullish().describe('How to read it — "slowly", "warm", "like a news anchor". Null for plain.')}),execute:async({text:e,voice:o,instructions:n},{sandbox:r,abortSignal:i})=>{let{audio:l}=await (0,a.generateSpeech)({model:t,text:e,voice:o??void 0,instructions:n??void 0,outputFormat:"mp3",abortSignal:i}),s=await f(r,_.audio,g(e.slice(0,60),l.format||"mp3"),l.uint8Array);return b(s)}})},k=async()=>{let e=await (0,u.resolveMediaRef)("transcription");if(!e)return null;let t=(0,u.buildTranscriptionModel)(e.ref,e.apiKey);return h({name:c.STUDIO_TOOLS.transcribe,description:"Turn an audio file — a recording, a voice memo, a meeting — into text. The transcript is saved as a file in the workspace; what comes back is its path and the text.",inputSchema:l.default.object({path:l.default.string().min(1).describe("The audio file: a path relative to the workspace, or an absolute one anywhere on this machine.")}),execute:async({path:e},{sandbox:o,abortSignal:i})=>{let l=await (0,n.readFile)(o.resolve(e)),s=await (0,a.transcribe)({model:t,audio:l,abortSignal:i}),u=s.segments.length?`
|
|
13
11
|
|
|
14
12
|
## Timeline
|
|
15
13
|
|
|
@@ -18,7 +16,13 @@ ${s.segments.map(e=>{var t;let o,n;return`- ${t=e.startSecond,o=Math.floor(t/60)
|
|
|
18
16
|
${s.text.trim()}${u}
|
|
19
17
|
`));return`${d}
|
|
20
18
|
|
|
21
|
-
${await o.fold(s.text,"transcript")}`}})},I=async()=>{let e=await (0,u.resolveMediaRef)("video");if(!e)return null;let t=(0,u.buildVideoModel)(e.ref,e.apiKey);return h({name:c.STUDIO_TOOLS.generate_video,description:"Make a short video and save it as a file in the workspace. Takes minutes. What comes back is its path.",inputSchema:l.default.object({prompt:l.default.string().describe("What happens: the scene, the motion, the camera, the mood. The video model does not see the job or the conversation, so nothing can be left implied."),aspectRatio:l.default.enum(["16:9","9:16"]).nullable().describe("Aspect ratio. Null for 16:9."),seconds:l.default.number().int().min(2).max(10).nullable().describe("Length in seconds, 2 to 10. Null for the provider's default.")}),execute:async({prompt:e,aspectRatio:o,seconds:n},{sandbox:r,abortSignal:i})=>{let{video:l}=await (0,a.experimental_generateVideo)({model:t,prompt:e,aspectRatio:o??"16:9",duration:n??void 0,abortSignal:i}),s=await f(r,_.videos,g(e,z(l.mediaType,"mp4")),l.uint8Array);return b(s)}})};async function y(){return(await Promise.all([v(x),v(S),v(k),v(I)])).filter(e=>null!==e)}async function v(e){try{return await e()}catch(e){return d.logger.warn(`studio: a tool could not be built — ${(0,p.errorToString)(e)}`),null}}e.s(["loadStudio",0,y]),o()}catch(e){o(e)}},!1),340697,e=>e.a(async(t,o)=>{try{var n=e.i(517435),r=e.i(333925),a=e.i(539904),i=e.i(993195),l=e.i(64774),s=e.i(437905),u=t([a,i,s]);async function c(e){let[t,o]=await Promise.all([!e||e===r.STUDIO_SERVER?(0,s.loadStudio)():[],e===r.STUDIO_SERVER?[]:(0,i.listToolNames)(e)]);return[...t.map(e=>({server:r.STUDIO_SERVER,name:e.name})),...o]}[a,i,s]=u.then?(await u)():u;let g=async()=>{let[e,t]=await Promise.all([(0,s.loadStudio)(),(0,i.listServerNames)()]);return[...e.length?[r.STUDIO_SERVER]:[],...t.map(e=>e.name)]};async function d(e,t){if(e===r.STUDIO_SERVER){let e=new Set(t);return(await (0,s.loadStudio)()).filter(t=>e.has(t.name)).map(e=>({name:e.name,description:e.description,inputSchema:n.default.toJSONSchema(e.inputSchema)}))}return(await (0,i.findToolSchemas)(e,t)).map(e=>({name:e.name,description:e.description??null,inputSchema:e.inputSchema??null}))}async function p(e,t,o,n,i){try{let a=t===r.STUDIO_SERVER?await m(e,o,n,i):await h(t,o,n);if("string"!=typeof a)return a;return{status:"ok",text:await e.fold(a,`${t}-${o}`)}}catch(e){if(e instanceof a.McpAuthRequiredError)return{status:"auth_required",server:t,authorizationUrl:e.authorizationUrl};return{status:"error",text:(0,l.errorToString)(e)}}}async function m(e,t,o,n){let a=(await (0,s.loadStudio)()).find(e=>e.name===t);if(!a)throw Error(`"${t}" is not in the ${r.STUDIO_SERVER} right now — the key that runs it is gone.`);return a.execute(o??{},{sandbox:e,abortSignal:n})}async function h(e,t,o){let n=function(e){let t=e??{},o=!0===t.isError;if(!Array.isArray(t.content)){let e=void 0===t.toolResult?"":"string"==typeof t.toolResult?t.toolResult:JSON.stringify(t.toolResult);return{status:o?"error":"ok",text:e||f(o)}}let n=t.content.map(e=>"text"===e.type&&"string"==typeof e.text?e.text:`[${e.type}${e.mimeType?` ${e.mimeType}`:""} — not shown]`).join("\n").trim();return{status:o?"error":"ok",text:n||f(o)}}(await a.mcpManager.callTool(e,t,o));return"ok"===n.status?n.text:n}let f=e=>e?"The tool failed without a message.":"Done.";e.s(["callConnectedTool",0,p,"findConnectedSchemas",0,d,"listConnectedServerNames",0,g,"listConnectedToolNames",0,c]),o()}catch(e){o(e)}},!1),859727,e=>{"use strict";var t=e.i(750227),o=e.i(691296),n=e.i(517435),r=e.i(51083),a=e.i(871096);e.s(["createWorkspaceTools",0,(e,i)=>{let l=(0,o.tool)({description:"Run a bash command.",inputSchema:n.default.object({command:n.default.string(),description:n.default.string().nullable().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:({command:t},{abortSignal:o})=>e.exec(t,{signal:o,env:i.env})});if(!i.write)return{[r.TOOL_NAMES.bash]:l};let s=(0,o.tool)({description:"Write a whole file — what was there is gone. Parent directories are created.",inputSchema:n.default.object({path:n.default.string().describe("Relative to the working directory — under one of its folders — or absolute"),content:n.default.string(),description:n.default.string().nullable().describe("One short line for the user: what this file is. Shown on their screen next to the path.")}),execute:async({path:o,content:n})=>{let r,i=e.resolve(o),l=(0,a.writeRefusal)(i);return l?l:(await e.writeFile(o,n),`Wrote ${(r=(0,t.relative)(e.cwd,i))&&!r.startsWith("..")?r:i} (${n.split("\n").length} lines)`)}});return{[r.TOOL_NAMES.bash]:l,[r.TOOL_NAMES.write_file]:s}}])},539904,e=>e.a(async(t,o)=>{try{var n,r=e.i(753955),a=e.i(940655),i=e.i(333925),l=e.i(938281),s=e.i(64774),u=e.i(993195),c=e.i(950262),d=t([u]);[u]=d.then?(await d)():d;class p extends Error{serverName;authorizationUrl;constructor(e,t){super(`MCP server "${e}" requires authorization`),this.serverName=e,this.authorizationUrl=t,this.name="McpAuthRequiredError"}}class m{store;serverName;oauth;callbackUrl;clientName;staticClient;lastAuthorizationUrl;constructor(e,t,o,n,r,a){this.store=e,this.serverName=t,this.oauth=o,this.callbackUrl=n,this.clientName=r,this.staticClient=a}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(e){this.oauth={...this.oauth,...e},await this.store.saveOAuth(this.serverName,this.oauth)}clientInformation(){return this.staticClient??this.oauth.clientInformation}async saveClientInformation(e){await this.persist({clientInformation:e})}tokens(){return this.oauth.tokens}async saveTokens(e){await this.persist({tokens:e})}authorizationServerInformation(){return this.oauth.authorizationServer}async saveAuthorizationServerInformation(e){await this.persist({authorizationServer:e})}codeVerifier(){if(!this.oauth.codeVerifier)throw Error("No code verifier saved");return this.oauth.codeVerifier}async saveCodeVerifier(e){await this.persist({codeVerifier:e})}state(){return crypto.randomUUID()}async saveState(e){await this.persist({state:e})}storedState(){return this.oauth.state}redirectToAuthorization(e){this.lastAuthorizationUrl=e}async invalidateCredentials(e){let t={...this.oauth};("all"===e||"client"===e)&&(t.clientInformation=void 0),("all"===e||"tokens"===e)&&(t.tokens=void 0),("all"===e||"verifier"===e)&&(t.codeVerifier=void 0),this.oauth=t,await this.store.saveOAuth(this.serverName,t)}}let h=globalThis;h.__thursdayMcpManager&&h.__thursdayMcpManager.dispose(),n={callbackUrl:new URL("/api/mcp/oauth/callback",i.APP_URL).href,clientName:i.APP_NAME},h.__thursdayMcpManager=new class e{store;sessions;connecting;idleTtlMs;callbackUrl;clientName;constructor(e,t){this.store=e,this.sessions=new Map,this.connecting=new Map,this.callbackUrl=t.callbackUrl,this.idleTtlMs=t.idleTtlMs??18e5,this.clientName=t.clientName??i.APP_NAME}async connect(e){let t=this.connecting.get(e);if(t)return t;let o=this.doConnect(e).finally(()=>this.connecting.delete(e));return this.connecting.set(e,o),o}async callTool(e,t,o){let n=await this.ensureClient(e);try{let r=await n.callTool({name:t,arguments:o});return this.touch(e),r}catch(t){if(t instanceof r.UnauthorizedError)throw await this.closeSession(e),new p(e);throw t}}async finishAuthorization(e){let t=e.get("state"),o=e.get("code");if(!t||!o)throw Error("OAuth callback is missing code or state");let n=await this.store.findByOAuthState(t);if(!n||!(0,c.isRemoteConfig)(n.config))throw Error("No server is waiting for this authorization");let a=this.providerFor(n),i=await (0,r.auth)(a,{serverUrl:n.config.url,authorizationCode:o,callbackState:t});if("AUTHORIZED"!==i)throw Error(`Token exchange ended in "${i}"`);return await a.invalidateCredentials("verifier"),await this.connect(n.name),n.name}async disconnect(e){await this.closeSession(e)}async dispose(){await Promise.all([...this.sessions.keys()].map(e=>this.closeSession(e)))}async doConnect(e){await this.closeSession(e);let t=await this.store.load(e);if(!t)throw Error(`Unknown MCP server "${e}"`);let o={};try{let n=await this.openClient(t,o),r=(await n.listTools()).tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema}));return this.adopt(e,n),await this.store.saveConnectionResult(e,{toolInfo:r,lastError:null}),l.logger.info(`mcp "${e}" connected — ${r.length} tools`),{status:"connected",tools:r}}catch(d){var n,a;let i;if(d instanceof r.UnauthorizedError||d?.cause instanceof r.UnauthorizedError){let t=o.href;if(t)return await this.store.saveConnectionResult(e,{toolInfo:[],lastError:"Authorization required — finish sign-in in the opened tab"}),{status:"auth_required",authorizationUrl:t}}let u=(n=d,a=t,i=(0,s.errorToString)(n),/\b40[13]\b/.test(i)&&/OAuth|register/i.test(i)&&(0,c.isRemoteConfig)(a.config)&&!a.config.oauthClient?"This server does not allow automatic client registration. Register an OAuth app with the provider and add its client ID and secret.":i);throw await this.store.saveConnectionResult(e,{toolInfo:[],lastError:u}),l.logger.warn(`mcp "${e}" failed — ${u}`),Error(u,{cause:d})}}async openClient(e,t={}){if((0,c.isRemoteConfig)(e.config)){let o=this.providerFor(e);try{return await (0,r.createMCPClient)({name:this.clientName,transport:{type:"http",url:e.config.url,headers:e.config.headers,authProvider:o,redirect:"follow"}})}finally{t.href=o.lastAuthorizationUrl?.href}}return(0,r.createMCPClient)({name:this.clientName,transport:new a.Experimental_StdioMCPTransport({command:e.config.command,args:e.config.args,env:e.config.env})})}providerFor(e){let t=(0,c.isRemoteConfig)(e.config)?e.config.oauthClient:void 0;return new m(this.store,e.name,e.oauth??{},this.callbackUrl,this.clientName,t&&{client_id:t.clientId,client_secret:t.clientSecret})}async ensureClient(e){let t=this.sessions.get(e);if(t)return t.client;let o=await this.connect(e);if("auth_required"===o.status)throw new p(e,o.authorizationUrl);let n=this.sessions.get(e);if(!n)throw Error(`Session for "${e}" vanished mid-connect`);return n.client}adopt(e,t){this.sessions.set(e,{client:t,idleTimer:this.armIdleTimer(e)})}touch(e){let t=this.sessions.get(e);t&&(clearTimeout(t.idleTimer),t.idleTimer=this.armIdleTimer(e))}armIdleTimer(e){let t=setTimeout(()=>{this.closeSession(e)},this.idleTtlMs);return t.unref?.(),t}async closeSession(e){let t=this.sessions.get(e);t&&(this.sessions.delete(e),clearTimeout(t.idleTimer),await t.client.close().catch(()=>{}))}}({load:e=>(0,u.findServer)(e),saveOAuth:(e,t)=>(0,u.saveOAuthData)(e,t),saveConnectionResult:(e,t)=>null===t.lastError?(0,u.syncServerTools)(e,t.toolInfo):(0,u.saveConnectionError)(e,t.lastError),findByOAuthState:e=>(0,u.findServerByOAuthState)(e)},n);let g=h.__thursdayMcpManager;e.s(["McpAuthRequiredError",0,p,"mcpManager",0,g]),o()}catch(e){o(e)}},!1),993195,e=>e.a(async(t,o)=>{try{var n=e.i(336763),r=e.i(533102),a=e.i(232347),i=e.i(876393),l=e.i(220376);e.i(950262);var s=t([i]);async function u(e){let[t]=await i.database.select().from(l.mcpServerTable).where((0,n.eq)(l.mcpServerTable.name,e));return t??null}[i]=s.then?(await s)():s;let g=()=>a.appEvents.emit({type:"mcp"});async function c(e,t){await i.database.transaction(async o=>{t.length&&await o.insert(l.mcpToolTable).values(t.map(t=>({...t,serverName:e}))).onConflictDoUpdate({target:[l.mcpToolTable.serverName,l.mcpToolTable.name],set:{description:d(l.mcpToolTable.description),inputSchema:d(l.mcpToolTable.inputSchema),outputSchema:d(l.mcpToolTable.outputSchema)}}),await o.delete(l.mcpToolTable).where(t.length?(0,n.and)((0,n.eq)(l.mcpToolTable.serverName,e),(0,n.notInArray)(l.mcpToolTable.name,t.map(e=>e.name))):(0,n.eq)(l.mcpToolTable.serverName,e)),await o.update(l.mcpServerTable).set({lastError:null,toolsSyncedAt:new Date}).where((0,n.eq)(l.mcpServerTable.name,e))}),g()}function d(e){return r.sql.raw(`excluded."${e.name}"`)}async function p(e,t){await i.database.update(l.mcpServerTable).set({lastError:t}).where((0,n.eq)(l.mcpServerTable.name,e)),g()}async function m(e,t){await i.database.update(l.mcpServerTable).set({oauth:t}).where((0,n.eq)(l.mcpServerTable.name,e)),g()}async function h(e){let[t]=await i.database.select().from(l.mcpServerTable).where(r.sql`json_extract(${l.mcpServerTable.oauth}, '$.state') = ${e}`);return t??null}e.s(["findPinnedTools",0,function(e){return i.database.select({server:l.mcpToolTable.serverName,name:l.mcpToolTable.name,description:l.mcpToolTable.description,inputSchema:l.mcpToolTable.inputSchema}).from(l.botMcpToolTable).innerJoin(l.mcpToolTable,(0,n.eq)(l.botMcpToolTable.toolId,l.mcpToolTable.id)).where((0,n.eq)(l.botMcpToolTable.botName,e)).orderBy(l.mcpToolTable.serverName,l.mcpToolTable.name)},"findServer",0,u,"findServerByOAuthState",0,h,"findToolSchemas",0,function(e,t){return t.length?i.database.select({name:l.mcpToolTable.name,description:l.mcpToolTable.description,inputSchema:l.mcpToolTable.inputSchema}).from(l.mcpToolTable).where((0,n.and)((0,n.eq)(l.mcpToolTable.serverName,e),(0,n.inArray)(l.mcpToolTable.name,t))).orderBy(l.mcpToolTable.name):Promise.resolve([])},"listServerNames",0,function(){return i.database.select({name:l.mcpServerTable.name}).from(l.mcpServerTable).orderBy(l.mcpServerTable.name)},"listToolNames",0,function(e){let t=i.database.select({server:l.mcpToolTable.serverName,name:l.mcpToolTable.name}).from(l.mcpToolTable);return e?t.where((0,n.eq)(l.mcpToolTable.serverName,e)).orderBy(l.mcpToolTable.name):t.orderBy(l.mcpToolTable.serverName,l.mcpToolTable.name)},"saveConnectionError",0,p,"saveOAuthData",0,m,"syncServerTools",0,c]),o()}catch(e){o(e)}},!1),950262,e=>{"use strict";var t=e.i(853205),o=e.i(900533);let n=t.z.object({url:t.z.url(),headers:t.z.record(t.z.string(),t.z.string()).optional(),oauthClient:t.z.object({clientId:t.z.string().min(1),clientSecret:t.z.string().optional()}).optional()}),r=t.z.object({command:t.z.string().min(1),args:t.z.array(t.z.string()).optional(),env:t.z.record(t.z.string(),t.z.string()).optional()}),a=t.z.union([n,r]),i=t.z.object({name:t.z.string(),description:t.z.string().optional(),inputSchema:t.z.looseObject({}).optional(),outputSchema:t.z.looseObject({}).optional()});t.z.object({clientInformation:t.z.looseObject({}).optional(),tokens:t.z.looseObject({}).optional(),authorizationServer:t.z.looseObject({}).optional(),codeVerifier:t.z.string().optional(),state:t.z.string().optional()});let l=t.z.object({name:t.z.string().min(1).max(40),config:a,toolCount:t.z.number().int(),lastError:t.z.string().nullish()}),s=i.extend({id:t.z.number().int(),description:t.z.string().nullish()});l.omit({toolCount:!0}).extend({tools:s.array().default([]),toolsSyncedAt:o.DateLikeSchema}),t.z.object({name:t.z.string().min(1,"Name is required").max(40).regex(/^[a-zA-Z0-9_-]+$/,"Only letters, numbers, - and _ are allowed"),config:a}),t.z.union([t.z.object({mcpServers:t.z.record(t.z.string(),a)}),t.z.record(t.z.string(),a)]),e.s(["isRemoteConfig",0,function(e){return"url"in e}])},343229,e=>{"use strict";var t=e.i(750227),o=e.i(333925),n=e.i(938281),r=e.i(64774),a=e.i(202837);let i=[(0,t.join)(o.APP_DIR,o.PATHS.skills.default),(0,t.join)(o.DATA_DIR,o.PATHS.skills.custom)];async function l(e,t){let o=[],i=new Set;for(let l of t){let t;try{t=await e.readdir(l,{withFileTypes:!0})}catch{continue}for(let s of t){let t,u;if(!s.isDirectory())continue;let c=`${l}/${s.name}`,d=`${c}/SKILL.md`;try{t=await e.readFile(d,"utf-8")}catch{continue}try{u=(0,a.parseFrontmatter)(t)}catch(e){n.logger.warn(`skill ${c}: SKILL.md front matter did not load — ${(0,r.errorToString)(e)}`);continue}!i.has(u.name)&&(i.add(u.name),u.disabled||o.push({name:u.name,description:u.description,path:c}))}}return o}e.s(["loadSkills",0,e=>l(e,i)])},202837,e=>{"use strict";e.i(912714);var t=e.i(750227),o=e.i(891906),n=e.i(333925),r=e.i(853205);r.z.enum(["custom","default"]);let a=r.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"),i=r.z.object({name:a,description:r.z.string().trim().min(1,"Description is required"),disabled:r.z.boolean().optional()});i.extend({content:r.z.string().trim().min(1,"Content is required")}),r.z.object({fileName:r.z.string().trim().min(1),base64:r.z.string().min(1)});var l=e.i(212389);function s(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!t)return{head:null,body:e.trim(),rest:e,fence:""};let o=e.slice(t[0].length);return{head:t[1]??null,body:o.trim(),rest:o,fence:t[0]}}(0,t.resolve)(n.APP_DIR,n.PATHS.skills.default),(0,t.resolve)(n.DATA_DIR,n.PATHS.skills.custom),e.s(["parseFrontmatter",0,function(e){let t,{head:n}=s(e);n||(0,l.publicError)("SKILL.md needs a YAML block with name and description");try{t=(0,o.parse)(n)}catch{(0,l.publicError)("SKILL.md frontmatter is not valid YAML")}let r=i.safeParse(t);return r.success||(0,l.publicError)(`SKILL.md frontmatter: ${r.error.issues[0]?.message??"invalid"}`),r.data},"splitFrontmatter",0,s],202837)},212389,e=>{"use strict";class t extends Error{message;constructor(e){super(e),this.message=e}}e.s(["publicError",0,function(e){throw new t(e)}])},610150,e=>{"use strict";let t=/[\u1100-\u11ff\u3040-\u30ff\u3130-\u318f\u4e00-\u9fff\uac00-\ud7af]/;e.s(["estimateTokens",0,function(e){let o=0,n=0;for(let r of e)t.test(r)?o+=1:n+=1;return Math.ceil(o/1.3+n/4)}])},128278,e=>{"use strict";var t=e.i(296194),o=e.i(691296),n=e.i(853205),r=e.i(548874),a=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.literal("error"),error:n.z.object({type:n.z.string(),message:n.z.string()})}))),i=(0,o.createJsonErrorResponseHandler)({errorSchema:a,errorToMessage:e=>e.error.message}),l=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({id:n.z.string(),type:n.z.literal("file"),filename:n.z.string(),mime_type:n.z.string(),size_bytes:n.z.number(),created_at:n.z.string(),downloadable:n.z.boolean().nullish()}))),s=class{constructor(e){this.config=e,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadFile({data:e,mediaType:t,filename:n,abortSignal:r,headers:a}){var s,u;let c=new Blob([(0,o.convertInlineFileDataToUint8Array)(e)],{type:t}),d=new FormData;null!=n?d.append("file",c,n):d.append("file",c);let{value:p}=await (0,o.postFormDataToApi)({url:`${this.config.baseURL}/files`,headers:(0,o.combineHeaders)(this.config.headers(),{"anthropic-beta":"files-api-2025-04-14"},a),formData:d,failedResponseHandler:i,successfulResponseHandler:(0,o.createJsonResponseHandler)(l),abortSignal:r,fetch:this.config.fetch});return{warnings:[],providerReference:{anthropic:p.id},mediaType:null!=(s=p.mime_type)?s:t,filename:null!=(u=p.filename)?u:n,providerMetadata:{anthropic:{filename:p.filename,mimeType:p.mime_type,sizeBytes:p.size_bytes,createdAt:p.created_at,...null!=p.downloadable?{downloadable:p.downloadable}:{}}}}}},u=n.z.object({type:n.z.string(),category:n.z.string().nullish(),explanation:n.z.string().nullish(),recommended_model:n.z.string().nullish()}),c=n.z.union([n.z.object({type:n.z.literal("code_execution_20250825"),tool_id:n.z.string()}),n.z.object({type:n.z.literal("code_execution_20260120"),tool_id:n.z.string()}),n.z.object({type:n.z.literal("direct")})]),d=n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("web_search_result_location"),cited_text:n.z.string(),url:n.z.string(),title:n.z.string().nullable(),encrypted_index:n.z.string()}),n.z.object({type:n.z.literal("page_location"),cited_text:n.z.string(),document_index:n.z.number(),document_title:n.z.string().nullable(),start_page_number:n.z.number(),end_page_number:n.z.number(),file_id:n.z.string().nullish()}),n.z.object({type:n.z.literal("char_location"),cited_text:n.z.string(),document_index:n.z.number(),document_title:n.z.string().nullable(),start_char_index:n.z.number(),end_char_index:n.z.number(),file_id:n.z.string().nullish()}),n.z.object({type:n.z.literal("content_block_location"),cited_text:n.z.string(),document_index:n.z.number(),document_title:n.z.string().nullable(),start_block_index:n.z.number(),end_block_index:n.z.number(),file_id:n.z.string().nullable()}),n.z.object({type:n.z.literal("search_result_location"),cited_text:n.z.string(),search_result_index:n.z.number(),source:n.z.string(),title:n.z.string().nullable(),start_block_index:n.z.number(),end_block_index:n.z.number()})]),p=n.z.union([n.z.string(),n.z.array(n.z.union([n.z.string(),n.z.object({type:n.z.literal("text"),text:n.z.string(),citations:n.z.array(n.z.json()).nullable().optional()})]))]),m=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.literal("message"),id:n.z.string().nullish(),model:n.z.string().nullish(),content:n.z.array(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("text"),text:n.z.string(),citations:n.z.array(d).nullable().optional()}),n.z.object({type:n.z.literal("thinking"),thinking:n.z.string(),signature:n.z.string()}),n.z.object({type:n.z.literal("redacted_thinking"),data:n.z.string()}),n.z.object({type:n.z.literal("compaction"),content:n.z.string()}),n.z.object({type:n.z.literal("tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.unknown(),caller:c.optional()}),n.z.object({type:n.z.literal("server_tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.record(n.z.string(),n.z.unknown()).nullish(),caller:c.optional()}),n.z.object({type:n.z.literal("mcp_tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.unknown(),server_name:n.z.string()}),n.z.object({type:n.z.literal("mcp_tool_result"),tool_use_id:n.z.string(),is_error:n.z.boolean(),content:p}),n.z.object({type:n.z.literal("web_fetch_tool_result"),tool_use_id:n.z.string(),caller:c.optional(),content:n.z.union([n.z.object({type:n.z.literal("web_fetch_result"),url:n.z.string(),retrieved_at:n.z.string().nullable(),content:n.z.object({type:n.z.literal("document"),title:n.z.string().nullable(),citations:n.z.object({enabled:n.z.boolean()}).optional(),source:n.z.union([n.z.object({type:n.z.literal("base64"),media_type:n.z.literal("application/pdf"),data:n.z.string()}),n.z.object({type:n.z.literal("text"),media_type:n.z.literal("text/plain"),data:n.z.string()})])})}),n.z.object({type:n.z.literal("web_fetch_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("web_search_tool_result"),tool_use_id:n.z.string(),caller:c.optional(),content:n.z.union([n.z.array(n.z.object({type:n.z.literal("web_search_result"),url:n.z.string(),title:n.z.string().nullable(),encrypted_content:n.z.string(),page_age:n.z.string().nullish()})),n.z.object({type:n.z.literal("web_search_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.union([n.z.object({type:n.z.literal("code_execution_result"),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("encrypted_code_execution_result"),encrypted_stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("code_execution_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("bash_code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("bash_code_execution_result"),content:n.z.array(n.z.object({type:n.z.literal("bash_code_execution_output"),file_id:n.z.string()})),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number()}),n.z.object({type:n.z.literal("bash_code_execution_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("text_editor_code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("text_editor_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_view_result"),content:n.z.string(),file_type:n.z.string(),num_lines:n.z.number().nullable(),start_line:n.z.number().nullable(),total_lines:n.z.number().nullable()}),n.z.object({type:n.z.literal("text_editor_code_execution_create_result"),is_file_update:n.z.boolean()}),n.z.object({type:n.z.literal("text_editor_code_execution_str_replace_result"),lines:n.z.array(n.z.string()).nullable(),new_lines:n.z.number().nullable(),new_start:n.z.number().nullable(),old_lines:n.z.number().nullable(),old_start:n.z.number().nullable()})])}),n.z.object({type:n.z.literal("tool_search_tool_result"),tool_use_id:n.z.string(),content:n.z.union([n.z.object({type:n.z.literal("tool_search_tool_search_result"),tool_references:n.z.array(n.z.object({type:n.z.literal("tool_reference"),tool_name:n.z.string()}))}),n.z.object({type:n.z.literal("tool_search_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("container_upload"),file_id:n.z.string()}),n.z.object({type:n.z.literal("advisor_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("advisor_result"),text:n.z.string(),stop_reason:n.z.string().nullish()}),n.z.object({type:n.z.literal("advisor_redacted_result"),encrypted_content:n.z.string(),stop_reason:n.z.string().nullish()}),n.z.object({type:n.z.literal("advisor_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("fallback")})])),stop_reason:n.z.string().nullish(),stop_sequence:n.z.string().nullish(),stop_details:u.nullish(),usage:n.z.looseObject({input_tokens:n.z.number(),output_tokens:n.z.number(),output_tokens_details:n.z.object({thinking_tokens:n.z.number().nullish()}).nullish(),cache_creation_input_tokens:n.z.number().nullish(),cache_read_input_tokens:n.z.number().nullish(),iterations:n.z.array(n.z.object({type:n.z.union([n.z.literal("compaction"),n.z.literal("message"),n.z.literal("advisor_message"),n.z.literal("fallback_message")]),model:n.z.string().nullish(),input_tokens:n.z.number(),output_tokens:n.z.number(),cache_creation_input_tokens:n.z.number().nullish(),cache_read_input_tokens:n.z.number().nullish()})).nullish()}),container:n.z.object({expires_at:n.z.string(),id:n.z.string(),skills:n.z.array(n.z.object({type:n.z.union([n.z.literal("anthropic"),n.z.literal("custom")]),skill_id:n.z.string(),version:n.z.string()})).nullish()}).nullish(),context_management:n.z.object({applied_edits:n.z.array(n.z.union([n.z.object({type:n.z.literal("clear_tool_uses_20250919"),cleared_tool_uses:n.z.number(),cleared_input_tokens:n.z.number()}),n.z.object({type:n.z.literal("clear_thinking_20251015"),cleared_thinking_turns:n.z.number(),cleared_input_tokens:n.z.number()}),n.z.object({type:n.z.literal("compact_20260112")})]))}).nullish()}))),h=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("message_start"),message:n.z.object({id:n.z.string().nullish(),model:n.z.string().nullish(),role:n.z.string().nullish(),usage:n.z.looseObject({input_tokens:n.z.number(),cache_creation_input_tokens:n.z.number().nullish(),cache_read_input_tokens:n.z.number().nullish()}),content:n.z.array(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.unknown(),caller:c.optional()})])).nullish(),stop_reason:n.z.string().nullish(),container:n.z.object({expires_at:n.z.string(),id:n.z.string()}).nullish()})}),n.z.object({type:n.z.literal("content_block_start"),index:n.z.number(),content_block:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("text"),text:n.z.string()}),n.z.object({type:n.z.literal("thinking"),thinking:n.z.string()}),n.z.object({type:n.z.literal("tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.record(n.z.string(),n.z.unknown()).optional(),caller:c.optional()}),n.z.object({type:n.z.literal("redacted_thinking"),data:n.z.string()}),n.z.object({type:n.z.literal("compaction"),content:n.z.string().nullish()}),n.z.object({type:n.z.literal("server_tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.record(n.z.string(),n.z.unknown()).nullish(),caller:c.optional()}),n.z.object({type:n.z.literal("mcp_tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.unknown(),server_name:n.z.string()}),n.z.object({type:n.z.literal("mcp_tool_result"),tool_use_id:n.z.string(),is_error:n.z.boolean(),content:p}),n.z.object({type:n.z.literal("web_fetch_tool_result"),tool_use_id:n.z.string(),caller:c.optional(),content:n.z.union([n.z.object({type:n.z.literal("web_fetch_result"),url:n.z.string(),retrieved_at:n.z.string().nullable(),content:n.z.object({type:n.z.literal("document"),title:n.z.string().nullable(),citations:n.z.object({enabled:n.z.boolean()}).optional(),source:n.z.union([n.z.object({type:n.z.literal("base64"),media_type:n.z.literal("application/pdf"),data:n.z.string()}),n.z.object({type:n.z.literal("text"),media_type:n.z.literal("text/plain"),data:n.z.string()})])})}),n.z.object({type:n.z.literal("web_fetch_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("web_search_tool_result"),tool_use_id:n.z.string(),caller:c.optional(),content:n.z.union([n.z.array(n.z.object({type:n.z.literal("web_search_result"),url:n.z.string(),title:n.z.string().nullable(),encrypted_content:n.z.string(),page_age:n.z.string().nullish()})),n.z.object({type:n.z.literal("web_search_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.union([n.z.object({type:n.z.literal("code_execution_result"),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("encrypted_code_execution_result"),encrypted_stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("code_execution_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("bash_code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("bash_code_execution_result"),content:n.z.array(n.z.object({type:n.z.literal("bash_code_execution_output"),file_id:n.z.string()})),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number()}),n.z.object({type:n.z.literal("bash_code_execution_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("text_editor_code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("text_editor_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_view_result"),content:n.z.string(),file_type:n.z.string(),num_lines:n.z.number().nullable(),start_line:n.z.number().nullable(),total_lines:n.z.number().nullable()}),n.z.object({type:n.z.literal("text_editor_code_execution_create_result"),is_file_update:n.z.boolean()}),n.z.object({type:n.z.literal("text_editor_code_execution_str_replace_result"),lines:n.z.array(n.z.string()).nullable(),new_lines:n.z.number().nullable(),new_start:n.z.number().nullable(),old_lines:n.z.number().nullable(),old_start:n.z.number().nullable()})])}),n.z.object({type:n.z.literal("tool_search_tool_result"),tool_use_id:n.z.string(),content:n.z.union([n.z.object({type:n.z.literal("tool_search_tool_search_result"),tool_references:n.z.array(n.z.object({type:n.z.literal("tool_reference"),tool_name:n.z.string()}))}),n.z.object({type:n.z.literal("tool_search_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("advisor_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("advisor_result"),text:n.z.string(),stop_reason:n.z.string().nullish()}),n.z.object({type:n.z.literal("advisor_redacted_result"),encrypted_content:n.z.string(),stop_reason:n.z.string().nullish()}),n.z.object({type:n.z.literal("advisor_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("fallback")})])}),n.z.object({type:n.z.literal("content_block_delta"),index:n.z.number(),delta:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("input_json_delta"),partial_json:n.z.string()}),n.z.object({type:n.z.literal("text_delta"),text:n.z.string()}),n.z.object({type:n.z.literal("thinking_delta"),thinking:n.z.string()}),n.z.object({type:n.z.literal("signature_delta"),signature:n.z.string()}),n.z.object({type:n.z.literal("compaction_delta"),content:n.z.string().nullish()}),n.z.object({type:n.z.literal("citations_delta"),citation:d})])}),n.z.object({type:n.z.literal("content_block_stop"),index:n.z.number()}),n.z.object({type:n.z.literal("error"),error:n.z.object({type:n.z.string(),message:n.z.string(),code:n.z.union([n.z.string(),n.z.number()]).nullish(),statusCode:n.z.number().nullish(),isRetryable:n.z.boolean().nullish(),data:n.z.unknown().nullish()})}),n.z.object({type:n.z.literal("message_delta"),delta:n.z.object({stop_reason:n.z.string().nullish(),stop_sequence:n.z.string().nullish(),stop_details:u.nullish(),container:n.z.object({expires_at:n.z.string(),id:n.z.string(),skills:n.z.array(n.z.object({type:n.z.union([n.z.literal("anthropic"),n.z.literal("custom")]),skill_id:n.z.string(),version:n.z.string()})).nullish()}).nullish()}),usage:n.z.looseObject({input_tokens:n.z.number().nullish(),output_tokens:n.z.number(),output_tokens_details:n.z.object({thinking_tokens:n.z.number().nullish()}).nullish(),cache_creation_input_tokens:n.z.number().nullish(),cache_read_input_tokens:n.z.number().nullish(),iterations:n.z.array(n.z.object({type:n.z.union([n.z.literal("compaction"),n.z.literal("message"),n.z.literal("advisor_message"),n.z.literal("fallback_message")]),model:n.z.string().nullish(),input_tokens:n.z.number(),output_tokens:n.z.number(),cache_creation_input_tokens:n.z.number().nullish(),cache_read_input_tokens:n.z.number().nullish()})).nullish()}),context_management:n.z.object({applied_edits:n.z.array(n.z.union([n.z.object({type:n.z.literal("clear_tool_uses_20250919"),cleared_tool_uses:n.z.number(),cleared_input_tokens:n.z.number()}),n.z.object({type:n.z.literal("clear_thinking_20251015"),cleared_thinking_turns:n.z.number(),cleared_input_tokens:n.z.number()}),n.z.object({type:n.z.literal("compact_20260112")})]))}).nullish()}),n.z.object({type:n.z.literal("message_stop")}),n.z.object({type:n.z.literal("ping")})]))),g=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({signature:n.z.string().optional(),redactedData:n.z.string().optional()}))),f=n.z.object({containerUpload:n.z.boolean().optional(),citations:n.z.object({enabled:n.z.boolean()}).optional(),title:n.z.string().optional(),context:n.z.string().optional()}),y=n.z.object({clearAt:n.z.literal("next_user_message").optional(),effort:n.z.enum(["low","medium","high","xhigh","max"]).optional(),toolChanges:n.z.array(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("tool_addition"),toolName:n.z.string()}),n.z.object({type:n.z.literal("tool_removal"),toolName:n.z.string()})])).optional()}),v=n.z.object({sendReasoning:n.z.boolean().optional(),structuredOutputMode:n.z.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:n.z.union([n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("adaptive"),display:n.z.enum(["omitted","summarized","updates"]).optional(),blockBinding:n.z.object({prefixMismatchBehavior:n.z.literal("drop_block")}).optional()}),n.z.object({type:n.z.literal("enabled"),budgetTokens:n.z.number().optional()}),n.z.object({type:n.z.literal("disabled")})]),n.z.object({type:n.z.never().optional(),blockBinding:n.z.object({prefixMismatchBehavior:n.z.literal("drop_block")})})]).optional(),disableParallelToolUse:n.z.boolean().optional(),cacheControl:n.z.object({type:n.z.literal("ephemeral"),ttl:n.z.union([n.z.literal("5m"),n.z.literal("1h")]).optional()}).optional(),metadata:n.z.object({userId:n.z.string().optional()}).optional(),mcpServers:n.z.array(n.z.object({type:n.z.literal("url"),name:n.z.string(),url:n.z.string(),authorizationToken:n.z.string().nullish(),toolConfiguration:n.z.object({enabled:n.z.boolean().nullish(),allowedTools:n.z.array(n.z.string()).nullish()}).nullish()})).optional(),container:n.z.object({id:n.z.string().optional(),skills:n.z.array(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("anthropic"),skillId:n.z.string(),version:n.z.string().optional()}),n.z.object({type:n.z.literal("custom"),providerReference:n.z.record(n.z.string(),n.z.string()),version:n.z.string().optional()})])).optional()}).optional(),toolStreaming:n.z.boolean().optional(),effort:n.z.enum(["low","medium","high","xhigh","max"]).optional(),taskBudget:n.z.object({type:n.z.literal("tokens"),total:n.z.number().int().min(2e4),remaining:n.z.number().int().min(0).optional()}).optional(),speed:n.z.enum(["fast","standard"]).optional(),serviceTier:n.z.enum(["auto","standard_only"]).optional(),inferenceGeo:n.z.enum(["us","global"]).optional(),fallbacks:n.z.union([n.z.literal("default"),n.z.array(n.z.object({model:n.z.string(),max_tokens:n.z.number().int().optional(),thinking:n.z.record(n.z.string(),n.z.unknown()).optional(),output_config:n.z.record(n.z.string(),n.z.unknown()).optional(),speed:n.z.enum(["fast","standard"]).optional()}))]).optional(),anthropicBeta:n.z.array(n.z.string()).optional(),contextManagement:n.z.object({edits:n.z.array(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("clear_tool_uses_20250919"),trigger:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("input_tokens"),value:n.z.number()}),n.z.object({type:n.z.literal("tool_uses"),value:n.z.number()})]).optional(),keep:n.z.object({type:n.z.literal("tool_uses"),value:n.z.number()}).optional(),clearAtLeast:n.z.object({type:n.z.literal("input_tokens"),value:n.z.number()}).optional(),clearToolInputs:n.z.boolean().optional(),excludeTools:n.z.array(n.z.string()).optional()}),n.z.object({type:n.z.literal("clear_thinking_20251015"),keep:n.z.union([n.z.literal("all"),n.z.object({type:n.z.literal("thinking_turns"),value:n.z.number()})]).optional()}),n.z.object({type:n.z.literal("compact_20260112"),trigger:n.z.object({type:n.z.literal("input_tokens"),value:n.z.number()}).optional(),pauseAfterCompaction:n.z.boolean().optional(),instructions:n.z.string().optional()})]))}).optional()}),_=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){var o;let n,r=null!=(o=null==(n=null==e?void 0:e.anthropic)?void 0:n.cacheControl)?o:null==n?void 0:n.cache_control;if(r)return t.canCache?(this.breakpointCount++,this.breakpointCount>4)?void this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum 4 cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`}):r:void this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${t.type}. It will be ignored.`})}getWarnings(){return this.warnings}},b=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({model:n.z.string(),maxUses:n.z.number().optional(),maxTokens:n.z.number().int().min(1024).optional(),caching:n.z.object({type:n.z.literal("ephemeral"),ttl:n.z.union([n.z.literal("5m"),n.z.literal("1h")])}).optional()}))),z=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("advisor_result"),text:n.z.string(),stopReason:n.z.string().optional()}),n.z.object({type:n.z.literal("advisor_redacted_result"),encryptedContent:n.z.string(),stopReason:n.z.string().optional()}),n.z.object({type:n.z.literal("advisor_tool_result_error"),errorCode:n.z.string()})]))),w=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({}).strict())),x=(0,o.createProviderExecutedToolFactory)({id:"anthropic.advisor_20260301",inputSchema:w,outputSchema:z,supportsDeferredResults:!0}),S=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({maxCharacters:n.z.number().optional()}))),k=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({command:n.z.enum(["view","create","str_replace","insert"]),path:n.z.string(),file_text:n.z.string().optional(),insert_line:n.z.number().int().optional(),new_str:n.z.string().optional(),insert_text:n.z.string().optional(),old_str:n.z.string().optional(),view_range:n.z.array(n.z.number().int()).optional()}))),I=(0,o.createProviderDefinedToolFactory)({id:"anthropic.text_editor_20250728",inputSchema:k}),T=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({maxUses:n.z.number().optional(),allowedDomains:n.z.array(n.z.string()).optional(),blockedDomains:n.z.array(n.z.string()).optional(),userLocation:n.z.object({type:n.z.literal("approximate"),city:n.z.string().optional(),region:n.z.string().optional(),country:n.z.string().optional(),timezone:n.z.string().optional()}).optional()}))),C=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.array(n.z.object({url:n.z.string(),title:n.z.string().nullable(),pageAge:n.z.string().nullable(),encryptedContent:n.z.string(),type:n.z.literal("web_search_result")})))),E=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({query:n.z.string()}))),M=(0,o.createProviderExecutedToolFactory)({id:"anthropic.web_search_20260209",inputSchema:E,outputSchema:C,supportsDeferredResults:!0}),j=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({maxUses:n.z.number().optional(),allowedDomains:n.z.array(n.z.string()).optional(),blockedDomains:n.z.array(n.z.string()).optional(),userLocation:n.z.object({type:n.z.literal("approximate"),city:n.z.string().optional(),region:n.z.string().optional(),country:n.z.string().optional(),timezone:n.z.string().optional()}).optional()}))),A=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.array(n.z.object({url:n.z.string(),title:n.z.string().nullable(),pageAge:n.z.string().nullable(),encryptedContent:n.z.string(),type:n.z.literal("web_search_result")})))),O=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({query:n.z.string()}))),R=(0,o.createProviderExecutedToolFactory)({id:"anthropic.web_search_20250305",inputSchema:O,outputSchema:A,supportsDeferredResults:!0}),N=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({maxUses:n.z.number().optional(),allowedDomains:n.z.array(n.z.string()).optional(),blockedDomains:n.z.array(n.z.string()).optional(),citations:n.z.object({enabled:n.z.boolean()}).optional(),maxContentTokens:n.z.number().optional()}))),P=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.literal("web_fetch_result"),url:n.z.string(),content:n.z.object({type:n.z.literal("document"),title:n.z.string().nullable(),citations:n.z.object({enabled:n.z.boolean()}).optional(),source:n.z.union([n.z.object({type:n.z.literal("base64"),mediaType:n.z.literal("application/pdf"),data:n.z.string()}),n.z.object({type:n.z.literal("text"),mediaType:n.z.literal("text/plain"),data:n.z.string()})])}),retrievedAt:n.z.string().nullable()}))),$=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({url:n.z.string()}))),q=(0,o.createProviderExecutedToolFactory)({id:"anthropic.web_fetch_20260209",inputSchema:$,outputSchema:P,supportsDeferredResults:!0}),L=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({maxUses:n.z.number().optional(),allowedDomains:n.z.array(n.z.string()).optional(),blockedDomains:n.z.array(n.z.string()).optional(),citations:n.z.object({enabled:n.z.boolean()}).optional(),maxContentTokens:n.z.number().optional()}))),D=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.literal("web_fetch_result"),url:n.z.string(),content:n.z.object({type:n.z.literal("document"),title:n.z.string().nullable(),citations:n.z.object({enabled:n.z.boolean()}).optional(),source:n.z.union([n.z.object({type:n.z.literal("base64"),mediaType:n.z.literal("application/pdf"),data:n.z.string()}),n.z.object({type:n.z.literal("text"),mediaType:n.z.literal("text/plain"),data:n.z.string()})])}),retrievedAt:n.z.string().nullable()}))),U=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({url:n.z.string()}))),F=(0,o.createProviderExecutedToolFactory)({id:"anthropic.web_fetch_20250910",inputSchema:U,outputSchema:D,supportsDeferredResults:!0});async function H({tools:e,toolChoice:n,disableParallelToolUse:r,cacheControlValidator:a,supportsStructuredOutput:i,supportsStrictTools:l,defaultEagerInputStreaming:s=!1}){var u,c;e=(null==e?void 0:e.length)?e:void 0;let d=[],p=new Set,m=a||new _;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:d,betas:p};let h=[];for(let t of e)switch(t.type){case"function":{let e=m.getCacheControl(t.providerOptions,{type:"tool definition",canCache:!0}),o=null==(u=t.providerOptions)?void 0:u.anthropic,n=null!=(c=null==o?void 0:o.eagerInputStreaming)?c:s,r=null==o?void 0:o.deferLoading,a=null==o?void 0:o.allowedCallers;l||null==t.strict||d.push({type:"unsupported",feature:"strict",details:`Tool '${t.name}' has strict: ${t.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),h.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e,...n?{eager_input_streaming:!0}:{},...!0===l&&null!=t.strict?{strict:t.strict}:{},...null!=r?{defer_loading:r}:{},...null!=a?{allowed_callers:a}:{},...null!=t.inputExamples?{input_examples:t.inputExamples.map(e=>e.input)}:{}}),!0===i&&p.add("structured-outputs-2025-11-13"),(null!=t.inputExamples||null!=a)&&p.add("advanced-tool-use-2025-11-20");break}case"provider":switch(t.id){case"anthropic.code_execution_20250522":p.add("code-execution-2025-05-22"),h.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break;case"anthropic.code_execution_20250825":p.add("code-execution-2025-08-25"),h.push({type:"code_execution_20250825",name:"code_execution"});break;case"anthropic.code_execution_20260120":h.push({type:"code_execution_20260120",name:"code_execution"});break;case"anthropic.computer_20250124":p.add("computer-use-2025-01-24"),h.push({name:"computer",type:"computer_20250124",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case"anthropic.computer_20251124":p.add("computer-use-2025-11-24"),h.push({name:"computer",type:"computer_20251124",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,enable_zoom:t.args.enableZoom,cache_control:void 0});break;case"anthropic.computer_20241022":p.add("computer-use-2024-10-22"),h.push({name:"computer",type:"computer_20241022",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case"anthropic.text_editor_20250124":p.add("computer-use-2025-01-24"),h.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break;case"anthropic.text_editor_20241022":p.add("computer-use-2024-10-22"),h.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break;case"anthropic.text_editor_20250429":p.add("computer-use-2025-01-24"),h.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break;case"anthropic.text_editor_20250728":{let e=await (0,o.validateTypes)({value:t.args,schema:S});h.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:e.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":p.add("computer-use-2025-01-24"),h.push({name:"bash",type:"bash_20250124",cache_control:void 0});break;case"anthropic.bash_20241022":p.add("computer-use-2024-10-22"),h.push({name:"bash",type:"bash_20241022",cache_control:void 0});break;case"anthropic.memory_20250818":p.add("context-management-2025-06-27"),h.push({name:"memory",type:"memory_20250818"});break;case"anthropic.web_fetch_20250910":{p.add("web-fetch-2025-09-10");let e=await (0,o.validateTypes)({value:t.args,schema:L});h.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{p.add("code-execution-web-tools-2026-02-09");let e=await (0,o.validateTypes)({value:t.args,schema:N});h.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let e=await (0,o.validateTypes)({value:t.args,schema:j});h.push({type:"web_search_20250305",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{p.add("code-execution-web-tools-2026-02-09");let e=await (0,o.validateTypes)({value:t.args,schema:T});h.push({type:"web_search_20260209",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":h.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break;case"anthropic.tool_search_bm25_20251119":h.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break;case"anthropic.advisor_20260301":{p.add("advisor-tool-2026-03-01");let e=await (0,o.validateTypes)({value:t.args,schema:b});h.push({type:"advisor_20260301",name:"advisor",model:e.model,...void 0!==e.maxUses&&{max_uses:e.maxUses},...void 0!==e.maxTokens&&{max_tokens:e.maxTokens},...void 0!==e.caching&&{caching:e.caching}});break}default:d.push({type:"unsupported",feature:`provider-defined tool ${t.id}`})}break;default:d.push({type:"unsupported",feature:`tool ${t}`})}if(null==n)return{tools:h,toolChoice:r?{type:"auto",disable_parallel_tool_use:r}:void 0,toolWarnings:d,betas:p};let g=n.type;switch(g){case"auto":return{tools:h,toolChoice:{type:"auto",disable_parallel_tool_use:r},toolWarnings:d,betas:p};case"required":return{tools:h,toolChoice:{type:"any",disable_parallel_tool_use:r},toolWarnings:d,betas:p};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:d,betas:p};case"tool":return{tools:h,toolChoice:{type:"tool",name:n.toolName,disable_parallel_tool_use:r},toolWarnings:d,betas:p};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${g}`})}}function B({usage:e,rawUsage:t}){var o,n,r,a,i;let l,s,u=null!=(o=e.cache_creation_input_tokens)?o:0,c=null!=(n=e.cache_read_input_tokens)?n:0,d=null!=(a=null==(r=e.output_tokens_details)?void 0:r.thinking_tokens)?a:void 0,p=null==(i=e.iterations)?void 0:i.some(e=>"fallback_message"===e.type);if(e.iterations&&e.iterations.length>0&&!p){let t=e.iterations.filter(e=>"compaction"===e.type||"message"===e.type);if(t.length>0){let e=t.reduce((e,t)=>({input:e.input+t.input_tokens,output:e.output+t.output_tokens}),{input:0,output:0});l=e.input,s=e.output}else l=e.input_tokens,s=e.output_tokens}else l=e.input_tokens,s=e.output_tokens;return{inputTokens:{total:l+u+c,noCache:l,cacheRead:c,cacheWrite:u},outputTokens:{total:s,text:null==d?void 0:s-d,reasoning:d},raw:null!=t?t:e}}var V=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.literal("code_execution_result"),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}))),J=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({code:n.z.string()}))),W=(0,o.createProviderExecutedToolFactory)({id:"anthropic.code_execution_20250522",inputSchema:J,outputSchema:V}),K=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("code_execution_result"),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("bash_code_execution_result"),content:n.z.array(n.z.object({type:n.z.literal("bash_code_execution_output"),file_id:n.z.string()})),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number()}),n.z.object({type:n.z.literal("bash_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_view_result"),content:n.z.string(),file_type:n.z.string(),num_lines:n.z.number().nullable(),start_line:n.z.number().nullable(),total_lines:n.z.number().nullable()}),n.z.object({type:n.z.literal("text_editor_code_execution_create_result"),is_file_update:n.z.boolean()}),n.z.object({type:n.z.literal("text_editor_code_execution_str_replace_result"),lines:n.z.array(n.z.string()).nullable(),new_lines:n.z.number().nullable(),new_start:n.z.number().nullable(),old_lines:n.z.number().nullable(),old_start:n.z.number().nullable()})]))),G=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("programmatic-tool-call"),code:n.z.string()}),n.z.object({type:n.z.literal("bash_code_execution"),command:n.z.string()}),n.z.discriminatedUnion("command",[n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("view"),path:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("create"),path:n.z.string(),file_text:n.z.string().nullish()}),n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("str_replace"),path:n.z.string(),old_str:n.z.string(),new_str:n.z.string()})])]))),Y=(0,o.createProviderExecutedToolFactory)({id:"anthropic.code_execution_20250825",inputSchema:G,outputSchema:K,supportsDeferredResults:!0}),X=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("code_execution_result"),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("encrypted_code_execution_result"),encrypted_stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("bash_code_execution_result"),content:n.z.array(n.z.object({type:n.z.literal("bash_code_execution_output"),file_id:n.z.string()})),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number()}),n.z.object({type:n.z.literal("bash_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_view_result"),content:n.z.string(),file_type:n.z.string(),num_lines:n.z.number().nullable(),start_line:n.z.number().nullable(),total_lines:n.z.number().nullable()}),n.z.object({type:n.z.literal("text_editor_code_execution_create_result"),is_file_update:n.z.boolean()}),n.z.object({type:n.z.literal("text_editor_code_execution_str_replace_result"),lines:n.z.array(n.z.string()).nullable(),new_lines:n.z.number().nullable(),new_start:n.z.number().nullable(),old_lines:n.z.number().nullable(),old_start:n.z.number().nullable()})]))),Z=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("programmatic-tool-call"),code:n.z.string()}),n.z.object({type:n.z.literal("bash_code_execution"),command:n.z.string()}),n.z.discriminatedUnion("command",[n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("view"),path:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("create"),path:n.z.string(),file_text:n.z.string().nullish()}),n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("str_replace"),path:n.z.string(),old_str:n.z.string(),new_str:n.z.string()})])]))),Q=(0,o.createProviderExecutedToolFactory)({id:"anthropic.code_execution_20260120",inputSchema:Z,outputSchema:X,supportsDeferredResults:!0}),ee=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.array(n.z.object({type:n.z.literal("tool_reference"),toolName:n.z.string()})))),et=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({pattern:n.z.string(),limit:n.z.number().optional()}))),eo=(0,o.createProviderExecutedToolFactory)({id:"anthropic.tool_search_regex_20251119",inputSchema:et,outputSchema:ee,supportsDeferredResults:!0});function en(e){try{if("string"==typeof e)return(0,o.secureJsonParse)(e);if("object"==typeof e&&null!==e)return e}catch(o){let t=null==e?void 0:e.errorCode;return{errorCode:"string"==typeof t?t:"unavailable"}}return{}}async function er({prompt:e,sendReasoning:n,warnings:r,cacheControlValidator:a,toolNameMapping:i}){var l,s,u,c,d,p,m,h,v,b,w,x,S,k,I,T,C,E,M,j,O,R,N,P;let $,q=new Set,L=function(e){let t,o=[];for(let n of e){let{role:e}=n;switch(e){case"system":(null==t?void 0:t.type)!=="system"&&(t={type:"system",messages:[]},o.push(t)),t.messages.push(n);break;case"assistant":(null==t?void 0:t.type)!=="assistant"&&(t={type:"assistant",messages:[]},o.push(t)),t.messages.push(n);break;case"user":case"tool":(null==t?void 0:t.type)!=="user"&&(t={type:"user",messages:[]},o.push(t)),t.messages.push(n);break;default:throw Error(`Unsupported role: ${e}`)}}return o}(e),U=a||new _,F=[];async function H(e){var t,n;let r=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:e,schema:f});return null!=(n=null==(t=null==r?void 0:r.citations)?void 0:t.enabled)&&n}async function B(e){var t;let n=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:e,schema:f});return null!=(t=null==n?void 0:n.containerUpload)&&t}async function J(e){let t=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:e,schema:f});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let e=0;e<L.length;e++){let a=L[e],f=e===L.length-1,_=a.type;switch(_){case"system":{let t=[];for(let{content:e,providerOptions:n}of a.messages){let r=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:n,schema:y}),a=null!=(l=null==r?void 0:r.toolChanges)?l:[],s=[];for(let t of((""!==e||0===a.length&&(null==r?void 0:r.clearAt)==null&&(null==r?void 0:r.effort)==null)&&s.push({type:"text",text:e,cache_control:U.getCacheControl(n,{type:"system message",canCache:!0})}),a))s.push({type:t.type,tool:{type:"tool_reference",name:i.toProviderToolName(t.toolName)}});t.push({content:s,clearAt:null==r?void 0:r.clearAt,effort:null==r?void 0:r.effort,toolChangeCount:a.length})}let n=t.reduce((e,t)=>e+t.toolChangeCount,0),s=t.some(e=>null!=e.clearAt||null!=e.effort);if(0!==e&&(null!=$||0!==n||s))for(let e of(q.add("mid-conversation-system-2026-04-07"),t))F.push({role:"system",content:e.content,...null!=e.clearAt&&{clear_at:e.clearAt},...null!=e.effort&&{output_config:{effort:e.effort}}}),e.toolChangeCount>0&&q.add("mid-conversation-tool-changes-2026-07-01"),null!=e.clearAt&&q.add("mid-conversation-system-clear-at-2026-08-21"),null!=e.effort&&q.add("mid-conversation-effort-2026-08-01");else{for(let e of(n>0&&r.push({type:"other",message:"tool changes on the initial system message are not supported by Anthropic. Configure the initial tool set via the tools option instead. The tool changes have been ignored."}),t))(null!=e.clearAt||null!=e.effort)&&r.push({type:"other",message:"clearAt and effort on the initial system message are not supported by Anthropic. These options have been ignored."});$=t.flatMap(e=>e.content.filter(e=>"text"===e.type))}break}case"user":{let e=[];for(let n of a.messages){let{role:a,content:i}=n;switch(a){case"user":for(let r=0;r<i.length;r++){let a=i[r],l=r===i.length-1,p=null!=(s=U.getCacheControl(a.providerOptions,{type:"user message part",canCache:!0}))?s:l?U.getCacheControl(n.providerOptions,{type:"user message",canCache:!0}):void 0;switch(a.type){case"text":e.push({type:"text",text:a.text,cache_control:p});break;case"file":switch(a.data.type){case"reference":{let t=(0,o.resolveProviderReference)({reference:a.data.reference,provider:"anthropic"});q.add("files-api-2025-04-14"),await B(a.providerOptions)?e.push({type:"container_upload",file_id:t}):"image"===(0,o.getTopLevelMediaType)(a.mediaType)?e.push({type:"image",source:{type:"file",file_id:t},cache_control:p}):e.push({type:"document",source:{type:"file",file_id:t},cache_control:p});break}case"text":{let t=await H(a.providerOptions),o=await J(a.providerOptions);e.push({type:"document",source:{type:"text",media_type:"text/plain",data:a.data.text},title:null!=(u=o.title)?u:a.filename,...o.context&&{context:o.context},...t&&{citations:{enabled:!0}},cache_control:p});break}case"url":case"data":{let n=(0,o.getTopLevelMediaType)(a.mediaType);if("image"===n)e.push({type:"image",source:"url"===a.data.type?{type:"url",url:a.data.url.toString()}:{type:"base64",media_type:(0,o.resolveFullMediaType)({part:a}),data:(0,o.convertToBase64)(a.data.data)},cache_control:p});else if("application"===n&&("url"===a.data.type?"application/pdf"===a.mediaType:"application/pdf"===(0,o.resolveFullMediaType)({part:a}))){q.add("pdfs-2024-09-25");let t=await H(a.providerOptions),n=await J(a.providerOptions);e.push({type:"document",source:"url"===a.data.type?{type:"url",url:a.data.url.toString()}:{type:"base64",media_type:"application/pdf",data:(0,o.convertToBase64)(a.data.data)},title:null!=(c=n.title)?c:a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:p})}else if("text/plain"===a.mediaType){let t=await H(a.providerOptions),n=await J(a.providerOptions);e.push({type:"document",source:"url"===a.data.type?{type:"url",url:a.data.url.toString()}:{type:"text",media_type:"text/plain",data:"string"==typeof(N=a.data.data)?new TextDecoder().decode((0,o.convertBase64ToUint8Array)(N)):new TextDecoder().decode(N)},title:null!=(d=n.title)?d:a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:p})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${a.mediaType}`})}}}}break;case"tool":for(let t=0;t<i.length;t++){let a,l=i[t];if("tool-approval-response"===l.type)continue;let s=l.output,u="providerOptions"in s?s.providerOptions:"content"===s.type?null==(p=s.value.find(e=>null!=e.providerOptions))?void 0:p.providerOptions:void 0,c=t===i.length-1,d=null!=(h=null!=(m=U.getCacheControl(l.providerOptions,{type:"tool result part",canCache:!0}))?m:U.getCacheControl(u,{type:"tool result output",canCache:!0}))?h:c?U.getCacheControl(n.providerOptions,{type:"tool result message",canCache:!0}):void 0;switch(s.type){case"content":a=s.value.map(e=>{var t;switch(e.type){case"text":return{type:"text",text:e.text};case"file":{let t=(0,o.getTopLevelMediaType)(e.mediaType);if("url"===e.data.type){if("image"===t)return{type:"image",source:{type:"url",url:e.data.url.toString()}};return{type:"document",source:{type:"url",url:e.data.url.toString()}}}if("data"===e.data.type){if("image"===t)return{type:"image",source:{type:"base64",media_type:(0,o.resolveFullMediaType)({part:e}),data:(0,o.convertToBase64)(e.data.data)}};if("application/pdf"===(0,o.resolveFullMediaType)({part:e}))return q.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:"application/pdf",data:(0,o.convertToBase64)(e.data.data)}};r.push({type:"other",message:`unsupported tool content part type: ${e.type} with media type: ${e.mediaType}`});return}r.push({type:"other",message:`unsupported tool content part type: ${e.type} with data type: ${e.data.type}`});return}case"custom":{let o=null==(t=e.providerOptions)?void 0:t.anthropic;if((null==o?void 0:o.type)==="tool-reference")return{type:"tool_reference",tool_name:o.toolName};r.push({type:"other",message:"unsupported custom tool content part"});return}default:return void r.push({type:"other",message:`unsupported tool content part type: ${e.type}`})}}).filter(o.isNonNullable);break;case"text":case"error-text":a=s.value;break;case"execution-denied":a=null!=(v=s.reason)?v:"Tool call execution denied.";break;default:a=JSON.stringify(s.value)}e.push({type:"tool_result",tool_use_id:l.toolCallId,content:a,is_error:"error-text"===s.type||"error-json"===s.type||void 0,cache_control:d})}break;default:throw Error(`Unsupported role: ${a}`)}}F.push({role:"user",content:e});break}case"assistant":{let e=[],t=new Set;for(let l=0;l<a.messages.length;l++){let s=a.messages[l],u=l===a.messages.length-1,{content:c}=s;for(let a=0;a<c.length;a++){let l=c[a],d=a===c.length-1,p=null!=(b=U.getCacheControl(l.providerOptions,{type:"assistant message part",canCache:!0}))?b:d?U.getCacheControl(s.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(l.type){case"text":{let t=null==(w=l.providerOptions)?void 0:w.anthropic;(null==t?void 0:t.type)==="compaction"?e.push({type:"compaction",content:l.text,cache_control:p}):e.push({type:"text",text:f&&u&&d?l.text.trim():l.text,...(null==t?void 0:t.citations)!=null&&{citations:t.citations},cache_control:p});break}case"reasoning":if(n){let t=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:l.providerOptions,schema:g});null!=t?null!=t.signature?(U.getCacheControl(l.providerOptions,{type:"thinking block",canCache:!1}),e.push({type:"thinking",thinking:l.text,signature:t.signature})):null!=t.redactedData?(U.getCacheControl(l.providerOptions,{type:"redacted thinking block",canCache:!1}),e.push({type:"redacted_thinking",data:t.redactedData})):r.push({type:"other",message:"unsupported reasoning metadata"}):r.push({type:"other",message:"unsupported reasoning metadata"})}else r.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"tool-call":{let o=ea(l.providerOptions);if(l.providerExecuted){let n=i.toProviderToolName(l.toolName);if((null==(S=null==(x=l.providerOptions)?void 0:x.anthropic)?void 0:S.type)==="mcp-tool-use"){t.add(l.toolCallId);let o=null==(I=null==(k=l.providerOptions)?void 0:k.anthropic)?void 0:I.serverName;if(null==o||"string"!=typeof o){r.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}e.push({type:"mcp_tool_use",id:l.toolCallId,name:l.toolName,input:l.input,server_name:o,cache_control:p})}else if("code_execution"===n&&null!=l.input&&"object"==typeof l.input&&"type"in l.input&&"string"==typeof l.input.type&&("bash_code_execution"===l.input.type||"text_editor_code_execution"===l.input.type)){let{type:t,...n}=l.input;e.push({type:"server_tool_use",id:l.toolCallId,name:t,input:n,...o&&{caller:o},cache_control:p})}else if("code_execution"===n&&null!=l.input&&"object"==typeof l.input&&"type"in l.input&&"programmatic-tool-call"===l.input.type){let{type:t,...n}=l.input;e.push({type:"server_tool_use",id:l.toolCallId,name:"code_execution",input:n,...o&&{caller:o},cache_control:p})}else"code_execution"===n||"web_fetch"===n||"web_search"===n||"tool_search_tool_regex"===n||"tool_search_tool_bm25"===n?e.push({type:"server_tool_use",id:l.toolCallId,name:n,input:l.input,...o&&{caller:o},cache_control:p}):"advisor"===n?e.push({type:"server_tool_use",id:l.toolCallId,name:"advisor",input:{},...o&&{caller:o},cache_control:p}):r.push({type:"other",message:`provider executed tool call for tool ${l.toolName} is not supported`});break}e.push({type:"tool_use",id:l.toolCallId,name:l.toolName,input:"object"!=typeof(P=l.input)||null===P||Array.isArray(P)?{rawInvalidInput:P}:P,...o&&{caller:o},cache_control:p});break}case"tool-result":{let n=i.toProviderToolName(l.toolName),a=ea(l.providerOptions);if(t.has(l.toolCallId)){let t=l.output;if("json"!==t.type&&"error-json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}e.push({type:"mcp_tool_result",tool_use_id:l.toolCallId,is_error:"error-json"===t.type,content:t.value,cache_control:p})}else if("code_execution"===n){let t=l.output;if("error-text"===t.type||"error-json"===t.type){let n={};try{"string"==typeof t.value?n=(0,o.secureJsonParse)(t.value):"object"==typeof t.value&&null!==t.value&&(n=t.value)}catch(e){}"code_execution_tool_result_error"===n.type?e.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:"code_execution_tool_result_error",error_code:null!=(T=n.errorCode)?T:"unknown"},cache_control:p}):e.push({type:"bash_code_execution_tool_result",tool_use_id:l.toolCallId,cache_control:p,content:{type:"bash_code_execution_tool_result_error",error_code:null!=(C=n.errorCode)?C:"unknown"}});break}if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}if(null==t.value||"object"!=typeof t.value||!("type"in t.value)||"string"!=typeof t.value.type){r.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${l.toolName}`});break}if("code_execution_result"===t.value.type){let n=await (0,o.validateTypes)({value:t.value,schema:V});e.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code,content:null!=(E=n.content)?E:[]},cache_control:p})}else if("encrypted_code_execution_result"===t.value.type){let n=await (0,o.validateTypes)({value:t.value,schema:X});"encrypted_code_execution_result"===n.type&&e.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:n.type,encrypted_stdout:n.encrypted_stdout,stderr:n.stderr,return_code:n.return_code,content:null!=(M=n.content)?M:[]},cache_control:p})}else{let n=await (0,o.validateTypes)({value:t.value,schema:K});"code_execution_result"===n.type?e.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code,content:null!=(j=n.content)?j:[]},cache_control:p}):"bash_code_execution_result"===n.type||"bash_code_execution_tool_result_error"===n.type?e.push({type:"bash_code_execution_tool_result",tool_use_id:l.toolCallId,cache_control:p,content:"bash_code_execution_result"===n.type?{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code,content:n.content}:n}):e.push({type:"text_editor_code_execution_tool_result",tool_use_id:l.toolCallId,cache_control:p,content:n})}break}if("web_fetch"===n){let t=l.output;if("error-json"===t.type){e.push({type:"web_fetch_tool_result",tool_use_id:l.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:null!=(O=en(t.value).errorCode)?O:"unavailable"},...a&&{caller:a},cache_control:p});break}if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}let n=await (0,o.validateTypes)({value:t.value,schema:D});e.push({type:"web_fetch_tool_result",tool_use_id:l.toolCallId,content:{type:"web_fetch_result",url:n.url,retrieved_at:n.retrievedAt,content:{type:"document",title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},...a&&{caller:a},cache_control:p});break}if("web_search"===n){let t=l.output;if("error-json"===t.type){e.push({type:"web_search_tool_result",tool_use_id:l.toolCallId,content:{type:"web_search_tool_result_error",error_code:null!=(R=en(t.value).errorCode)?R:"unavailable"},...a&&{caller:a},cache_control:p});break}if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}let n=await (0,o.validateTypes)({value:t.value,schema:A});e.push({type:"web_search_tool_result",tool_use_id:l.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),...a&&{caller:a},cache_control:p});break}if("tool_search_tool_regex"===n||"tool_search_tool_bm25"===n){let t=l.output;if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}let n=(await (0,o.validateTypes)({value:t.value,schema:ee})).map(e=>({type:"tool_reference",tool_name:e.toolName}));e.push({type:"tool_search_tool_result",tool_use_id:l.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:n},cache_control:p});break}if("advisor"===n){let t=l.output;if("json"!==t.type&&"error-json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}let n=await (0,o.validateTypes)({value:t.value,schema:z});"advisor_result"===n.type?e.push({type:"advisor_tool_result",tool_use_id:l.toolCallId,content:{type:"advisor_result",text:n.text,...void 0!==n.stopReason&&{stop_reason:n.stopReason}},cache_control:p}):"advisor_redacted_result"===n.type?e.push({type:"advisor_tool_result",tool_use_id:l.toolCallId,content:{type:"advisor_redacted_result",encrypted_content:n.encryptedContent,...void 0!==n.stopReason&&{stop_reason:n.stopReason}},cache_control:p}):e.push({type:"advisor_tool_result",tool_use_id:l.toolCallId,content:{type:"advisor_tool_result_error",error_code:n.errorCode},cache_control:p});break}r.push({type:"other",message:`provider executed tool result for tool ${l.toolName} is not supported`})}}}}F.push({role:"assistant",content:function(e){let t=[],o=[];function n(){t.push(...o.filter(e=>"tool_use"!==e.type),...o.filter(e=>"tool_use"===e.type)),o=[]}for(let r of e)"thinking"===r.type||"redacted_thinking"===r.type?(n(),t.push(r)):o.push(r);return n(),t}(e)});break}default:throw Error(`content type: ${_}`)}}return{prompt:{system:$,messages:F},betas:q}}function ea(e){var t;let o=null==(t=null==e?void 0:e.anthropic)?void 0:t.caller;return((null==o?void 0:o.type)==="code_execution_20250825"||(null==o?void 0:o.type)==="code_execution_20260120")&&o.toolId?{type:o.type,tool_id:o.toolId}:(null==o?void 0:o.type)==="direct"?{type:"direct"}:void 0}function ei({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";default:return"other"}}var el=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),es=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function eu(e){return"boolean"!=typeof e&&(0,o.isRecord)(e)?ec(e):e}function ec(e){var t;let o,n={};if(null!=e.$ref)return{$ref:e.$ref};null!=e.$schema&&(n.$schema=e.$schema),null!=e.$id&&(n.$id=e.$id),null!=e.title&&(n.title=e.title),null!=e.description&&(n.description=e.description),void 0!==e.default&&(n.default=e.default),void 0!==e.const&&(n.const=e.const),null!=e.enum&&(n.enum=e.enum),null!=e.type&&(n.type=e.type),null!=e.anyOf?n.anyOf=e.anyOf.map(eu):null!=e.oneOf&&(n.anyOf=e.oneOf.map(eu)),null!=e.allOf&&(n.allOf=e.allOf.map(eu)),null!=e.definitions&&(n.definitions=Object.fromEntries(Object.entries(e.definitions).map(([e,t])=>[e,eu(t)]))),null!=e.$defs&&(n.$defs=Object.fromEntries(Object.entries(e.$defs).map(([e,t])=>[e,eu(t)]))),("object"===e.type||null!=e.properties)&&(null!=e.properties&&(n.properties=Object.fromEntries(Object.entries(e.properties).map(([e,t])=>[e,eu(t)]))),n.additionalProperties=!1,null!=e.required&&(n.required=e.required)),null!=e.items&&(n.items=Array.isArray(e.items)?e.items.map(eu):eu(e.items)),"string"==typeof e.format&&el.has(e.format)&&(n.format=e.format);let r=(t=e,o=es.flatMap(e=>{var o;let n=t[e];return null==n||!1===n?[]:`${e.replace(/[A-Z]/g,e=>` ${e.toLowerCase()}`)}: ${"string"==typeof(o=n)?o:JSON.stringify(o)}`}),"string"!=typeof t.format||el.has(t.format)||o.push(`format: ${t.format}`),0===o.length?void 0:`${o.join("; ")}.`);return null!=r&&(n.description=null==n.description?r:`${n.description}
|
|
19
|
+
${await o.fold(s.text,"transcript")}`}})},I=async()=>{let e=await (0,u.resolveMediaRef)("video");if(!e)return null;let t=(0,u.buildVideoModel)(e.ref,e.apiKey);return h({name:c.STUDIO_TOOLS.generate_video,description:"Make a short video and save it as a file in the workspace. Takes minutes. What comes back is its path.",inputSchema:l.default.object({prompt:l.default.string().describe("What happens: the scene, the motion, the camera, the mood. The video model does not see the job or the conversation, so nothing can be left implied."),aspectRatio:l.default.enum(["16:9","9:16"]).nullish().describe("Aspect ratio. Null for 16:9."),seconds:l.default.number().int().min(2).max(10).nullish().describe("Length in seconds, 2 to 10. Null for the provider's default.")}),execute:async({prompt:e,aspectRatio:o,seconds:n},{sandbox:r,abortSignal:i})=>{let{video:l}=await (0,a.experimental_generateVideo)({model:t,prompt:e,aspectRatio:o??"16:9",duration:n??void 0,abortSignal:i}),s=await f(r,_.videos,g(e,z(l.mediaType,"mp4")),l.uint8Array);return b(s)}})};async function y(){return(await Promise.all([v(x),v(S),v(k),v(I)])).filter(e=>null!==e)}async function v(e){try{return await e()}catch(e){return d.logger.warn(`studio: a tool could not be built — ${(0,p.errorToString)(e)}`),null}}e.s(["loadStudio",0,y]),o()}catch(e){o(e)}},!1),340697,e=>e.a(async(t,o)=>{try{var n=e.i(517435),r=e.i(333925),a=e.i(539904),i=e.i(993195),l=e.i(64774),s=e.i(437905),u=t([a,i,s]);async function c(e){let[t,o]=await Promise.all([!e||e===r.STUDIO_SERVER?(0,s.loadStudio)():[],e===r.STUDIO_SERVER?[]:(0,i.listToolNames)(e)]);return[...t.map(e=>({server:r.STUDIO_SERVER,name:e.name})),...o]}[a,i,s]=u.then?(await u)():u;let g=async()=>{let[e,t]=await Promise.all([(0,s.loadStudio)(),(0,i.listServerNames)()]);return[...e.length?[r.STUDIO_SERVER]:[],...t.map(e=>e.name)]};async function d(e,t){if(e===r.STUDIO_SERVER){let e=new Set(t);return(await (0,s.loadStudio)()).filter(t=>e.has(t.name)).map(e=>({name:e.name,description:e.description,inputSchema:n.default.toJSONSchema(e.inputSchema)}))}return(await (0,i.findToolSchemas)(e,t)).map(e=>({name:e.name,description:e.description??null,inputSchema:e.inputSchema??null}))}async function p(e,t,o,n,i){try{let a=t===r.STUDIO_SERVER?await m(e,o,n,i):await h(t,o,n);if("string"!=typeof a)return a;return{status:"ok",text:await e.fold(a,`${t}-${o}`)}}catch(e){if(e instanceof a.McpAuthRequiredError)return{status:"auth_required",server:t,authorizationUrl:e.authorizationUrl};return{status:"error",text:(0,l.errorToString)(e)}}}async function m(e,t,o,n){let a=(await (0,s.loadStudio)()).find(e=>e.name===t);if(!a)throw Error(`"${t}" is not in the ${r.STUDIO_SERVER} right now — the key that runs it is gone.`);return a.execute(o??{},{sandbox:e,abortSignal:n})}async function h(e,t,o){let n=function(e){let t=e??{},o=!0===t.isError;if(!Array.isArray(t.content)){let e=void 0===t.toolResult?"":"string"==typeof t.toolResult?t.toolResult:JSON.stringify(t.toolResult);return{status:o?"error":"ok",text:e||f(o)}}let n=t.content.map(e=>"text"===e.type&&"string"==typeof e.text?e.text:`[${e.type}${e.mimeType?` ${e.mimeType}`:""} — not shown]`).join("\n").trim();return{status:o?"error":"ok",text:n||f(o)}}(await a.mcpManager.callTool(e,t,o));return"ok"===n.status?n.text:n}let f=e=>e?"The tool failed without a message.":"Done.";e.s(["callConnectedTool",0,p,"findConnectedSchemas",0,d,"listConnectedServerNames",0,g,"listConnectedToolNames",0,c]),o()}catch(e){o(e)}},!1),859727,e=>{"use strict";var t=e.i(750227),o=e.i(691296),n=e.i(517435),r=e.i(51083),a=e.i(871096),i=e.i(73829);let l=`## The shell here
|
|
20
|
+
|
|
21
|
+
Every command is a new shell: \`cd\`, exported variables and an activated venv are gone by the next one — chain what depends on the last step into a single command.
|
|
22
|
+
|
|
23
|
+
Nothing is watching it. A command that stops to ask never gets an answer and is killed after ${i.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.
|
|
24
|
+
|
|
25
|
+
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.`;e.s(["createWorkspaceTools",0,(e,i)=>{let s=!0===i.guide,u=(0,o.tool)({description:"Run a bash command.",inputSchema:n.default.object({command:n.default.string(),description:n.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:t},{abortSignal:o})=>{let n=await e.exec(t,{signal:o,env:i.env});return s?(s=!1,{...n,guide:l}):n}});if(!i.write)return{[r.TOOL_NAMES.bash]:u};let c=(0,o.tool)({description:"Write a whole file — what was there is gone. Parent directories are created.",inputSchema:n.default.object({path:n.default.string().describe("Relative to the working directory — under one of its folders — or absolute"),content:n.default.string(),description:n.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:o,content:n})=>{let r,i=e.resolve(o),l=(0,a.writeRefusal)(i);return l?l:(await e.writeFile(o,n),`Wrote ${(r=(0,t.relative)(e.cwd,i))&&!r.startsWith("..")?r:i} (${n.split("\n").length} lines)`)}});return{[r.TOOL_NAMES.bash]:u,[r.TOOL_NAMES.write_file]:c}}])},539904,e=>e.a(async(t,o)=>{try{var n,r=e.i(753955),a=e.i(940655),i=e.i(333925),l=e.i(938281),s=e.i(64774),u=e.i(993195),c=e.i(950262),d=t([u]);[u]=d.then?(await d)():d;class p extends Error{serverName;authorizationUrl;constructor(e,t){super(`MCP server "${e}" requires authorization`),this.serverName=e,this.authorizationUrl=t,this.name="McpAuthRequiredError"}}class m{store;serverName;oauth;callbackUrl;clientName;staticClient;lastAuthorizationUrl;constructor(e,t,o,n,r,a){this.store=e,this.serverName=t,this.oauth=o,this.callbackUrl=n,this.clientName=r,this.staticClient=a}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(e){this.oauth={...this.oauth,...e},await this.store.saveOAuth(this.serverName,this.oauth)}clientInformation(){return this.staticClient??this.oauth.clientInformation}async saveClientInformation(e){await this.persist({clientInformation:e})}tokens(){return this.oauth.tokens}async saveTokens(e){await this.persist({tokens:e})}authorizationServerInformation(){return this.oauth.authorizationServer}async saveAuthorizationServerInformation(e){await this.persist({authorizationServer:e})}codeVerifier(){if(!this.oauth.codeVerifier)throw Error("No code verifier saved");return this.oauth.codeVerifier}async saveCodeVerifier(e){await this.persist({codeVerifier:e})}state(){return crypto.randomUUID()}async saveState(e){await this.persist({state:e})}storedState(){return this.oauth.state}redirectToAuthorization(e){this.lastAuthorizationUrl=e}async invalidateCredentials(e){let t={...this.oauth};("all"===e||"client"===e)&&(t.clientInformation=void 0),("all"===e||"tokens"===e)&&(t.tokens=void 0),("all"===e||"verifier"===e)&&(t.codeVerifier=void 0),this.oauth=t,await this.store.saveOAuth(this.serverName,t)}}let h=globalThis;h.__thursdayMcpManager&&h.__thursdayMcpManager.dispose(),n={callbackUrl:new URL("/api/mcp/oauth/callback",i.APP_URL).href,clientName:i.APP_NAME},h.__thursdayMcpManager=new class e{store;sessions;connecting;idleTtlMs;callbackUrl;clientName;constructor(e,t){this.store=e,this.sessions=new Map,this.connecting=new Map,this.callbackUrl=t.callbackUrl,this.idleTtlMs=t.idleTtlMs??18e5,this.clientName=t.clientName??i.APP_NAME}async connect(e){let t=this.connecting.get(e);if(t)return t;let o=this.doConnect(e).finally(()=>this.connecting.delete(e));return this.connecting.set(e,o),o}async callTool(e,t,o){let n=await this.ensureClient(e);try{let r=await n.callTool({name:t,arguments:o});return this.touch(e),r}catch(t){if(t instanceof r.UnauthorizedError)throw await this.closeSession(e),new p(e);throw t}}async finishAuthorization(e){let t=e.get("state"),o=e.get("code");if(!t||!o)throw Error("OAuth callback is missing code or state");let n=await this.store.findByOAuthState(t);if(!n||!(0,c.isRemoteConfig)(n.config))throw Error("No server is waiting for this authorization");let a=this.providerFor(n),i=await (0,r.auth)(a,{serverUrl:n.config.url,authorizationCode:o,callbackState:t});if("AUTHORIZED"!==i)throw Error(`Token exchange ended in "${i}"`);return await a.invalidateCredentials("verifier"),await this.connect(n.name),n.name}async disconnect(e){await this.closeSession(e)}async dispose(){await Promise.all([...this.sessions.keys()].map(e=>this.closeSession(e)))}async doConnect(e){await this.closeSession(e);let t=await this.store.load(e);if(!t)throw Error(`Unknown MCP server "${e}"`);let o={};try{let n=await this.openClient(t,o),r=(await n.listTools()).tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema}));return this.adopt(e,n),await this.store.saveConnectionResult(e,{toolInfo:r,lastError:null}),l.logger.info(`mcp "${e}" connected — ${r.length} tools`),{status:"connected",tools:r}}catch(d){var n,a;let i;if(d instanceof r.UnauthorizedError||d?.cause instanceof r.UnauthorizedError){let t=o.href;if(t)return await this.store.saveConnectionResult(e,{toolInfo:[],lastError:"Authorization required — finish sign-in in the opened tab"}),{status:"auth_required",authorizationUrl:t}}let u=(n=d,a=t,i=(0,s.errorToString)(n),/\b40[13]\b/.test(i)&&/OAuth|register/i.test(i)&&(0,c.isRemoteConfig)(a.config)&&!a.config.oauthClient?"This server does not allow automatic client registration. Register an OAuth app with the provider and add its client ID and secret.":i);throw await this.store.saveConnectionResult(e,{toolInfo:[],lastError:u}),l.logger.warn(`mcp "${e}" failed — ${u}`),Error(u,{cause:d})}}async openClient(e,t={}){if((0,c.isRemoteConfig)(e.config)){let o=this.providerFor(e);try{return await (0,r.createMCPClient)({name:this.clientName,transport:{type:"http",url:e.config.url,headers:e.config.headers,authProvider:o,redirect:"follow"}})}finally{t.href=o.lastAuthorizationUrl?.href}}return(0,r.createMCPClient)({name:this.clientName,transport:new a.Experimental_StdioMCPTransport({command:e.config.command,args:e.config.args,env:e.config.env})})}providerFor(e){let t=(0,c.isRemoteConfig)(e.config)?e.config.oauthClient:void 0;return new m(this.store,e.name,e.oauth??{},this.callbackUrl,this.clientName,t&&{client_id:t.clientId,client_secret:t.clientSecret})}async ensureClient(e){let t=this.sessions.get(e);if(t)return t.client;let o=await this.connect(e);if("auth_required"===o.status)throw new p(e,o.authorizationUrl);let n=this.sessions.get(e);if(!n)throw Error(`Session for "${e}" vanished mid-connect`);return n.client}adopt(e,t){this.sessions.set(e,{client:t,idleTimer:this.armIdleTimer(e)})}touch(e){let t=this.sessions.get(e);t&&(clearTimeout(t.idleTimer),t.idleTimer=this.armIdleTimer(e))}armIdleTimer(e){let t=setTimeout(()=>{this.closeSession(e)},this.idleTtlMs);return t.unref?.(),t}async closeSession(e){let t=this.sessions.get(e);t&&(this.sessions.delete(e),clearTimeout(t.idleTimer),await t.client.close().catch(()=>{}))}}({load:e=>(0,u.findServer)(e),saveOAuth:(e,t)=>(0,u.saveOAuthData)(e,t),saveConnectionResult:(e,t)=>null===t.lastError?(0,u.syncServerTools)(e,t.toolInfo):(0,u.saveConnectionError)(e,t.lastError),findByOAuthState:e=>(0,u.findServerByOAuthState)(e)},n);let g=h.__thursdayMcpManager;e.s(["McpAuthRequiredError",0,p,"mcpManager",0,g]),o()}catch(e){o(e)}},!1),993195,e=>e.a(async(t,o)=>{try{var n=e.i(336763),r=e.i(533102),a=e.i(232347),i=e.i(876393),l=e.i(220376);e.i(950262);var s=t([i]);async function u(e){let[t]=await i.database.select().from(l.mcpServerTable).where((0,n.eq)(l.mcpServerTable.name,e));return t??null}[i]=s.then?(await s)():s;let g=()=>a.appEvents.emit({type:"mcp"});async function c(e,t){await i.database.transaction(async o=>{t.length&&await o.insert(l.mcpToolTable).values(t.map(t=>({...t,serverName:e}))).onConflictDoUpdate({target:[l.mcpToolTable.serverName,l.mcpToolTable.name],set:{description:d(l.mcpToolTable.description),inputSchema:d(l.mcpToolTable.inputSchema),outputSchema:d(l.mcpToolTable.outputSchema)}}),await o.delete(l.mcpToolTable).where(t.length?(0,n.and)((0,n.eq)(l.mcpToolTable.serverName,e),(0,n.notInArray)(l.mcpToolTable.name,t.map(e=>e.name))):(0,n.eq)(l.mcpToolTable.serverName,e)),await o.update(l.mcpServerTable).set({lastError:null,toolsSyncedAt:new Date}).where((0,n.eq)(l.mcpServerTable.name,e))}),g()}function d(e){return r.sql.raw(`excluded."${e.name}"`)}async function p(e,t){await i.database.update(l.mcpServerTable).set({lastError:t}).where((0,n.eq)(l.mcpServerTable.name,e)),g()}async function m(e,t){await i.database.update(l.mcpServerTable).set({oauth:t}).where((0,n.eq)(l.mcpServerTable.name,e)),g()}async function h(e){let[t]=await i.database.select().from(l.mcpServerTable).where(r.sql`json_extract(${l.mcpServerTable.oauth}, '$.state') = ${e}`);return t??null}e.s(["findPinnedTools",0,function(e){return i.database.select({server:l.mcpToolTable.serverName,name:l.mcpToolTable.name,description:l.mcpToolTable.description,inputSchema:l.mcpToolTable.inputSchema}).from(l.botMcpToolTable).innerJoin(l.mcpToolTable,(0,n.eq)(l.botMcpToolTable.toolId,l.mcpToolTable.id)).where((0,n.eq)(l.botMcpToolTable.botName,e)).orderBy(l.mcpToolTable.serverName,l.mcpToolTable.name)},"findServer",0,u,"findServerByOAuthState",0,h,"findToolSchemas",0,function(e,t){return t.length?i.database.select({name:l.mcpToolTable.name,description:l.mcpToolTable.description,inputSchema:l.mcpToolTable.inputSchema}).from(l.mcpToolTable).where((0,n.and)((0,n.eq)(l.mcpToolTable.serverName,e),(0,n.inArray)(l.mcpToolTable.name,t))).orderBy(l.mcpToolTable.name):Promise.resolve([])},"listServerNames",0,function(){return i.database.select({name:l.mcpServerTable.name}).from(l.mcpServerTable).orderBy(l.mcpServerTable.name)},"listToolNames",0,function(e){let t=i.database.select({server:l.mcpToolTable.serverName,name:l.mcpToolTable.name}).from(l.mcpToolTable);return e?t.where((0,n.eq)(l.mcpToolTable.serverName,e)).orderBy(l.mcpToolTable.name):t.orderBy(l.mcpToolTable.serverName,l.mcpToolTable.name)},"saveConnectionError",0,p,"saveOAuthData",0,m,"syncServerTools",0,c]),o()}catch(e){o(e)}},!1),950262,e=>{"use strict";var t=e.i(853205),o=e.i(900533);let n=t.z.object({url:t.z.url(),headers:t.z.record(t.z.string(),t.z.string()).optional(),oauthClient:t.z.object({clientId:t.z.string().min(1),clientSecret:t.z.string().optional()}).optional()}),r=t.z.object({command:t.z.string().min(1),args:t.z.array(t.z.string()).optional(),env:t.z.record(t.z.string(),t.z.string()).optional()}),a=t.z.union([n,r]),i=t.z.object({name:t.z.string(),description:t.z.string().optional(),inputSchema:t.z.looseObject({}).optional(),outputSchema:t.z.looseObject({}).optional()});t.z.object({clientInformation:t.z.looseObject({}).optional(),tokens:t.z.looseObject({}).optional(),authorizationServer:t.z.looseObject({}).optional(),codeVerifier:t.z.string().optional(),state:t.z.string().optional()});let l=t.z.object({name:t.z.string().min(1).max(40),config:a,toolCount:t.z.number().int(),lastError:t.z.string().nullish()}),s=i.extend({id:t.z.number().int(),description:t.z.string().nullish()});l.omit({toolCount:!0}).extend({tools:s.array().default([]),toolsSyncedAt:o.DateLikeSchema}),t.z.object({name:t.z.string().min(1,"Name is required").max(40).regex(/^[a-zA-Z0-9_-]+$/,"Only letters, numbers, - and _ are allowed"),config:a}),t.z.union([t.z.object({mcpServers:t.z.record(t.z.string(),a)}),t.z.record(t.z.string(),a)]),e.s(["isRemoteConfig",0,function(e){return"url"in e}])},343229,e=>{"use strict";var t=e.i(750227),o=e.i(333925),n=e.i(938281),r=e.i(64774),a=e.i(202837);let i=[(0,t.join)(o.APP_DIR,o.PATHS.skills.default),(0,t.join)(o.DATA_DIR,o.PATHS.skills.custom)];async function l(e,t){let o=[],i=new Set;for(let l of t){let t;try{t=await e.readdir(l,{withFileTypes:!0})}catch{continue}for(let s of t){let t,u;if(!s.isDirectory())continue;let c=`${l}/${s.name}`,d=`${c}/SKILL.md`;try{t=await e.readFile(d,"utf-8")}catch{continue}try{u=(0,a.parseFrontmatter)(t)}catch(e){n.logger.warn(`skill ${c}: SKILL.md front matter did not load — ${(0,r.errorToString)(e)}`);continue}!i.has(u.name)&&(i.add(u.name),u.disabled||o.push({name:u.name,description:u.description,path:c}))}}return o}e.s(["loadSkills",0,e=>l(e,i)])},202837,e=>{"use strict";e.i(912714);var t=e.i(750227),o=e.i(891906),n=e.i(333925),r=e.i(853205);r.z.enum(["custom","default"]);let a=r.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"),i=r.z.object({name:a,description:r.z.string().trim().min(1,"Description is required"),disabled:r.z.boolean().optional()});i.extend({content:r.z.string().trim().min(1,"Content is required")}),r.z.object({fileName:r.z.string().trim().min(1),base64:r.z.string().min(1)});var l=e.i(212389);function s(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!t)return{head:null,body:e.trim(),rest:e,fence:""};let o=e.slice(t[0].length);return{head:t[1]??null,body:o.trim(),rest:o,fence:t[0]}}(0,t.resolve)(n.APP_DIR,n.PATHS.skills.default),(0,t.resolve)(n.DATA_DIR,n.PATHS.skills.custom),e.s(["parseFrontmatter",0,function(e){let t,{head:n}=s(e);n||(0,l.publicError)("SKILL.md needs a YAML block with name and description");try{t=(0,o.parse)(n)}catch{(0,l.publicError)("SKILL.md frontmatter is not valid YAML")}let r=i.safeParse(t);return r.success||(0,l.publicError)(`SKILL.md frontmatter: ${r.error.issues[0]?.message??"invalid"}`),r.data},"splitFrontmatter",0,s],202837)},212389,e=>{"use strict";class t extends Error{message;constructor(e){super(e),this.message=e}}e.s(["publicError",0,function(e){throw new t(e)}])},610150,e=>{"use strict";let t=/[\u1100-\u11ff\u3040-\u30ff\u3130-\u318f\u4e00-\u9fff\uac00-\ud7af]/;function o(e){let o=0,n=0;for(let r of e)t.test(r)?o+=1:n+=1;return Math.ceil(o/1.3+n/4)}e.s(["estimateTokens",0,o,"sectionTokens",0,function(e){return e.split(/\n(?=## )/).map(e=>({name:e.startsWith("## ")?e.slice(3,e.indexOf("\n")):"identity",tokens:o(e)})).sort((e,t)=>t.tokens-e.tokens)}])},128278,e=>{"use strict";var t=e.i(296194),o=e.i(691296),n=e.i(853205),r=e.i(548874),a=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.literal("error"),error:n.z.object({type:n.z.string(),message:n.z.string()})}))),i=(0,o.createJsonErrorResponseHandler)({errorSchema:a,errorToMessage:e=>e.error.message}),l=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({id:n.z.string(),type:n.z.literal("file"),filename:n.z.string(),mime_type:n.z.string(),size_bytes:n.z.number(),created_at:n.z.string(),downloadable:n.z.boolean().nullish()}))),s=class{constructor(e){this.config=e,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadFile({data:e,mediaType:t,filename:n,abortSignal:r,headers:a}){var s,u;let c=new Blob([(0,o.convertInlineFileDataToUint8Array)(e)],{type:t}),d=new FormData;null!=n?d.append("file",c,n):d.append("file",c);let{value:p}=await (0,o.postFormDataToApi)({url:`${this.config.baseURL}/files`,headers:(0,o.combineHeaders)(this.config.headers(),{"anthropic-beta":"files-api-2025-04-14"},a),formData:d,failedResponseHandler:i,successfulResponseHandler:(0,o.createJsonResponseHandler)(l),abortSignal:r,fetch:this.config.fetch});return{warnings:[],providerReference:{anthropic:p.id},mediaType:null!=(s=p.mime_type)?s:t,filename:null!=(u=p.filename)?u:n,providerMetadata:{anthropic:{filename:p.filename,mimeType:p.mime_type,sizeBytes:p.size_bytes,createdAt:p.created_at,...null!=p.downloadable?{downloadable:p.downloadable}:{}}}}}},u=n.z.object({type:n.z.string(),category:n.z.string().nullish(),explanation:n.z.string().nullish(),recommended_model:n.z.string().nullish()}),c=n.z.union([n.z.object({type:n.z.literal("code_execution_20250825"),tool_id:n.z.string()}),n.z.object({type:n.z.literal("code_execution_20260120"),tool_id:n.z.string()}),n.z.object({type:n.z.literal("direct")})]),d=n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("web_search_result_location"),cited_text:n.z.string(),url:n.z.string(),title:n.z.string().nullable(),encrypted_index:n.z.string()}),n.z.object({type:n.z.literal("page_location"),cited_text:n.z.string(),document_index:n.z.number(),document_title:n.z.string().nullable(),start_page_number:n.z.number(),end_page_number:n.z.number(),file_id:n.z.string().nullish()}),n.z.object({type:n.z.literal("char_location"),cited_text:n.z.string(),document_index:n.z.number(),document_title:n.z.string().nullable(),start_char_index:n.z.number(),end_char_index:n.z.number(),file_id:n.z.string().nullish()}),n.z.object({type:n.z.literal("content_block_location"),cited_text:n.z.string(),document_index:n.z.number(),document_title:n.z.string().nullable(),start_block_index:n.z.number(),end_block_index:n.z.number(),file_id:n.z.string().nullable()}),n.z.object({type:n.z.literal("search_result_location"),cited_text:n.z.string(),search_result_index:n.z.number(),source:n.z.string(),title:n.z.string().nullable(),start_block_index:n.z.number(),end_block_index:n.z.number()})]),p=n.z.union([n.z.string(),n.z.array(n.z.union([n.z.string(),n.z.object({type:n.z.literal("text"),text:n.z.string(),citations:n.z.array(n.z.json()).nullable().optional()})]))]),m=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.literal("message"),id:n.z.string().nullish(),model:n.z.string().nullish(),content:n.z.array(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("text"),text:n.z.string(),citations:n.z.array(d).nullable().optional()}),n.z.object({type:n.z.literal("thinking"),thinking:n.z.string(),signature:n.z.string()}),n.z.object({type:n.z.literal("redacted_thinking"),data:n.z.string()}),n.z.object({type:n.z.literal("compaction"),content:n.z.string()}),n.z.object({type:n.z.literal("tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.unknown(),caller:c.optional()}),n.z.object({type:n.z.literal("server_tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.record(n.z.string(),n.z.unknown()).nullish(),caller:c.optional()}),n.z.object({type:n.z.literal("mcp_tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.unknown(),server_name:n.z.string()}),n.z.object({type:n.z.literal("mcp_tool_result"),tool_use_id:n.z.string(),is_error:n.z.boolean(),content:p}),n.z.object({type:n.z.literal("web_fetch_tool_result"),tool_use_id:n.z.string(),caller:c.optional(),content:n.z.union([n.z.object({type:n.z.literal("web_fetch_result"),url:n.z.string(),retrieved_at:n.z.string().nullable(),content:n.z.object({type:n.z.literal("document"),title:n.z.string().nullable(),citations:n.z.object({enabled:n.z.boolean()}).optional(),source:n.z.union([n.z.object({type:n.z.literal("base64"),media_type:n.z.literal("application/pdf"),data:n.z.string()}),n.z.object({type:n.z.literal("text"),media_type:n.z.literal("text/plain"),data:n.z.string()})])})}),n.z.object({type:n.z.literal("web_fetch_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("web_search_tool_result"),tool_use_id:n.z.string(),caller:c.optional(),content:n.z.union([n.z.array(n.z.object({type:n.z.literal("web_search_result"),url:n.z.string(),title:n.z.string().nullable(),encrypted_content:n.z.string(),page_age:n.z.string().nullish()})),n.z.object({type:n.z.literal("web_search_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.union([n.z.object({type:n.z.literal("code_execution_result"),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("encrypted_code_execution_result"),encrypted_stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("code_execution_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("bash_code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("bash_code_execution_result"),content:n.z.array(n.z.object({type:n.z.literal("bash_code_execution_output"),file_id:n.z.string()})),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number()}),n.z.object({type:n.z.literal("bash_code_execution_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("text_editor_code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("text_editor_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_view_result"),content:n.z.string(),file_type:n.z.string(),num_lines:n.z.number().nullable(),start_line:n.z.number().nullable(),total_lines:n.z.number().nullable()}),n.z.object({type:n.z.literal("text_editor_code_execution_create_result"),is_file_update:n.z.boolean()}),n.z.object({type:n.z.literal("text_editor_code_execution_str_replace_result"),lines:n.z.array(n.z.string()).nullable(),new_lines:n.z.number().nullable(),new_start:n.z.number().nullable(),old_lines:n.z.number().nullable(),old_start:n.z.number().nullable()})])}),n.z.object({type:n.z.literal("tool_search_tool_result"),tool_use_id:n.z.string(),content:n.z.union([n.z.object({type:n.z.literal("tool_search_tool_search_result"),tool_references:n.z.array(n.z.object({type:n.z.literal("tool_reference"),tool_name:n.z.string()}))}),n.z.object({type:n.z.literal("tool_search_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("container_upload"),file_id:n.z.string()}),n.z.object({type:n.z.literal("advisor_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("advisor_result"),text:n.z.string(),stop_reason:n.z.string().nullish()}),n.z.object({type:n.z.literal("advisor_redacted_result"),encrypted_content:n.z.string(),stop_reason:n.z.string().nullish()}),n.z.object({type:n.z.literal("advisor_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("fallback")})])),stop_reason:n.z.string().nullish(),stop_sequence:n.z.string().nullish(),stop_details:u.nullish(),usage:n.z.looseObject({input_tokens:n.z.number(),output_tokens:n.z.number(),output_tokens_details:n.z.object({thinking_tokens:n.z.number().nullish()}).nullish(),cache_creation_input_tokens:n.z.number().nullish(),cache_read_input_tokens:n.z.number().nullish(),iterations:n.z.array(n.z.object({type:n.z.union([n.z.literal("compaction"),n.z.literal("message"),n.z.literal("advisor_message"),n.z.literal("fallback_message")]),model:n.z.string().nullish(),input_tokens:n.z.number(),output_tokens:n.z.number(),cache_creation_input_tokens:n.z.number().nullish(),cache_read_input_tokens:n.z.number().nullish()})).nullish()}),container:n.z.object({expires_at:n.z.string(),id:n.z.string(),skills:n.z.array(n.z.object({type:n.z.union([n.z.literal("anthropic"),n.z.literal("custom")]),skill_id:n.z.string(),version:n.z.string()})).nullish()}).nullish(),context_management:n.z.object({applied_edits:n.z.array(n.z.union([n.z.object({type:n.z.literal("clear_tool_uses_20250919"),cleared_tool_uses:n.z.number(),cleared_input_tokens:n.z.number()}),n.z.object({type:n.z.literal("clear_thinking_20251015"),cleared_thinking_turns:n.z.number(),cleared_input_tokens:n.z.number()}),n.z.object({type:n.z.literal("compact_20260112")})]))}).nullish()}))),h=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("message_start"),message:n.z.object({id:n.z.string().nullish(),model:n.z.string().nullish(),role:n.z.string().nullish(),usage:n.z.looseObject({input_tokens:n.z.number(),cache_creation_input_tokens:n.z.number().nullish(),cache_read_input_tokens:n.z.number().nullish()}),content:n.z.array(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.unknown(),caller:c.optional()})])).nullish(),stop_reason:n.z.string().nullish(),container:n.z.object({expires_at:n.z.string(),id:n.z.string()}).nullish()})}),n.z.object({type:n.z.literal("content_block_start"),index:n.z.number(),content_block:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("text"),text:n.z.string()}),n.z.object({type:n.z.literal("thinking"),thinking:n.z.string()}),n.z.object({type:n.z.literal("tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.record(n.z.string(),n.z.unknown()).optional(),caller:c.optional()}),n.z.object({type:n.z.literal("redacted_thinking"),data:n.z.string()}),n.z.object({type:n.z.literal("compaction"),content:n.z.string().nullish()}),n.z.object({type:n.z.literal("server_tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.record(n.z.string(),n.z.unknown()).nullish(),caller:c.optional()}),n.z.object({type:n.z.literal("mcp_tool_use"),id:n.z.string(),name:n.z.string(),input:n.z.unknown(),server_name:n.z.string()}),n.z.object({type:n.z.literal("mcp_tool_result"),tool_use_id:n.z.string(),is_error:n.z.boolean(),content:p}),n.z.object({type:n.z.literal("web_fetch_tool_result"),tool_use_id:n.z.string(),caller:c.optional(),content:n.z.union([n.z.object({type:n.z.literal("web_fetch_result"),url:n.z.string(),retrieved_at:n.z.string().nullable(),content:n.z.object({type:n.z.literal("document"),title:n.z.string().nullable(),citations:n.z.object({enabled:n.z.boolean()}).optional(),source:n.z.union([n.z.object({type:n.z.literal("base64"),media_type:n.z.literal("application/pdf"),data:n.z.string()}),n.z.object({type:n.z.literal("text"),media_type:n.z.literal("text/plain"),data:n.z.string()})])})}),n.z.object({type:n.z.literal("web_fetch_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("web_search_tool_result"),tool_use_id:n.z.string(),caller:c.optional(),content:n.z.union([n.z.array(n.z.object({type:n.z.literal("web_search_result"),url:n.z.string(),title:n.z.string().nullable(),encrypted_content:n.z.string(),page_age:n.z.string().nullish()})),n.z.object({type:n.z.literal("web_search_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.union([n.z.object({type:n.z.literal("code_execution_result"),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("encrypted_code_execution_result"),encrypted_stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("code_execution_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("bash_code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("bash_code_execution_result"),content:n.z.array(n.z.object({type:n.z.literal("bash_code_execution_output"),file_id:n.z.string()})),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number()}),n.z.object({type:n.z.literal("bash_code_execution_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("text_editor_code_execution_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("text_editor_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_view_result"),content:n.z.string(),file_type:n.z.string(),num_lines:n.z.number().nullable(),start_line:n.z.number().nullable(),total_lines:n.z.number().nullable()}),n.z.object({type:n.z.literal("text_editor_code_execution_create_result"),is_file_update:n.z.boolean()}),n.z.object({type:n.z.literal("text_editor_code_execution_str_replace_result"),lines:n.z.array(n.z.string()).nullable(),new_lines:n.z.number().nullable(),new_start:n.z.number().nullable(),old_lines:n.z.number().nullable(),old_start:n.z.number().nullable()})])}),n.z.object({type:n.z.literal("tool_search_tool_result"),tool_use_id:n.z.string(),content:n.z.union([n.z.object({type:n.z.literal("tool_search_tool_search_result"),tool_references:n.z.array(n.z.object({type:n.z.literal("tool_reference"),tool_name:n.z.string()}))}),n.z.object({type:n.z.literal("tool_search_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("advisor_tool_result"),tool_use_id:n.z.string(),content:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("advisor_result"),text:n.z.string(),stop_reason:n.z.string().nullish()}),n.z.object({type:n.z.literal("advisor_redacted_result"),encrypted_content:n.z.string(),stop_reason:n.z.string().nullish()}),n.z.object({type:n.z.literal("advisor_tool_result_error"),error_code:n.z.string()})])}),n.z.object({type:n.z.literal("fallback")})])}),n.z.object({type:n.z.literal("content_block_delta"),index:n.z.number(),delta:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("input_json_delta"),partial_json:n.z.string()}),n.z.object({type:n.z.literal("text_delta"),text:n.z.string()}),n.z.object({type:n.z.literal("thinking_delta"),thinking:n.z.string()}),n.z.object({type:n.z.literal("signature_delta"),signature:n.z.string()}),n.z.object({type:n.z.literal("compaction_delta"),content:n.z.string().nullish()}),n.z.object({type:n.z.literal("citations_delta"),citation:d})])}),n.z.object({type:n.z.literal("content_block_stop"),index:n.z.number()}),n.z.object({type:n.z.literal("error"),error:n.z.object({type:n.z.string(),message:n.z.string(),code:n.z.union([n.z.string(),n.z.number()]).nullish(),statusCode:n.z.number().nullish(),isRetryable:n.z.boolean().nullish(),data:n.z.unknown().nullish()})}),n.z.object({type:n.z.literal("message_delta"),delta:n.z.object({stop_reason:n.z.string().nullish(),stop_sequence:n.z.string().nullish(),stop_details:u.nullish(),container:n.z.object({expires_at:n.z.string(),id:n.z.string(),skills:n.z.array(n.z.object({type:n.z.union([n.z.literal("anthropic"),n.z.literal("custom")]),skill_id:n.z.string(),version:n.z.string()})).nullish()}).nullish()}),usage:n.z.looseObject({input_tokens:n.z.number().nullish(),output_tokens:n.z.number(),output_tokens_details:n.z.object({thinking_tokens:n.z.number().nullish()}).nullish(),cache_creation_input_tokens:n.z.number().nullish(),cache_read_input_tokens:n.z.number().nullish(),iterations:n.z.array(n.z.object({type:n.z.union([n.z.literal("compaction"),n.z.literal("message"),n.z.literal("advisor_message"),n.z.literal("fallback_message")]),model:n.z.string().nullish(),input_tokens:n.z.number(),output_tokens:n.z.number(),cache_creation_input_tokens:n.z.number().nullish(),cache_read_input_tokens:n.z.number().nullish()})).nullish()}),context_management:n.z.object({applied_edits:n.z.array(n.z.union([n.z.object({type:n.z.literal("clear_tool_uses_20250919"),cleared_tool_uses:n.z.number(),cleared_input_tokens:n.z.number()}),n.z.object({type:n.z.literal("clear_thinking_20251015"),cleared_thinking_turns:n.z.number(),cleared_input_tokens:n.z.number()}),n.z.object({type:n.z.literal("compact_20260112")})]))}).nullish()}),n.z.object({type:n.z.literal("message_stop")}),n.z.object({type:n.z.literal("ping")})]))),g=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({signature:n.z.string().optional(),redactedData:n.z.string().optional()}))),f=n.z.object({containerUpload:n.z.boolean().optional(),citations:n.z.object({enabled:n.z.boolean()}).optional(),title:n.z.string().optional(),context:n.z.string().optional()}),y=n.z.object({clearAt:n.z.literal("next_user_message").optional(),effort:n.z.enum(["low","medium","high","xhigh","max"]).optional(),toolChanges:n.z.array(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("tool_addition"),toolName:n.z.string()}),n.z.object({type:n.z.literal("tool_removal"),toolName:n.z.string()})])).optional()}),v=n.z.object({sendReasoning:n.z.boolean().optional(),structuredOutputMode:n.z.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:n.z.union([n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("adaptive"),display:n.z.enum(["omitted","summarized","updates"]).optional(),blockBinding:n.z.object({prefixMismatchBehavior:n.z.literal("drop_block")}).optional()}),n.z.object({type:n.z.literal("enabled"),budgetTokens:n.z.number().optional()}),n.z.object({type:n.z.literal("disabled")})]),n.z.object({type:n.z.never().optional(),blockBinding:n.z.object({prefixMismatchBehavior:n.z.literal("drop_block")})})]).optional(),disableParallelToolUse:n.z.boolean().optional(),cacheControl:n.z.object({type:n.z.literal("ephemeral"),ttl:n.z.union([n.z.literal("5m"),n.z.literal("1h")]).optional()}).optional(),metadata:n.z.object({userId:n.z.string().optional()}).optional(),mcpServers:n.z.array(n.z.object({type:n.z.literal("url"),name:n.z.string(),url:n.z.string(),authorizationToken:n.z.string().nullish(),toolConfiguration:n.z.object({enabled:n.z.boolean().nullish(),allowedTools:n.z.array(n.z.string()).nullish()}).nullish()})).optional(),container:n.z.object({id:n.z.string().optional(),skills:n.z.array(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("anthropic"),skillId:n.z.string(),version:n.z.string().optional()}),n.z.object({type:n.z.literal("custom"),providerReference:n.z.record(n.z.string(),n.z.string()),version:n.z.string().optional()})])).optional()}).optional(),toolStreaming:n.z.boolean().optional(),effort:n.z.enum(["low","medium","high","xhigh","max"]).optional(),taskBudget:n.z.object({type:n.z.literal("tokens"),total:n.z.number().int().min(2e4),remaining:n.z.number().int().min(0).optional()}).optional(),speed:n.z.enum(["fast","standard"]).optional(),serviceTier:n.z.enum(["auto","standard_only"]).optional(),inferenceGeo:n.z.enum(["us","global"]).optional(),fallbacks:n.z.union([n.z.literal("default"),n.z.array(n.z.object({model:n.z.string(),max_tokens:n.z.number().int().optional(),thinking:n.z.record(n.z.string(),n.z.unknown()).optional(),output_config:n.z.record(n.z.string(),n.z.unknown()).optional(),speed:n.z.enum(["fast","standard"]).optional()}))]).optional(),anthropicBeta:n.z.array(n.z.string()).optional(),contextManagement:n.z.object({edits:n.z.array(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("clear_tool_uses_20250919"),trigger:n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("input_tokens"),value:n.z.number()}),n.z.object({type:n.z.literal("tool_uses"),value:n.z.number()})]).optional(),keep:n.z.object({type:n.z.literal("tool_uses"),value:n.z.number()}).optional(),clearAtLeast:n.z.object({type:n.z.literal("input_tokens"),value:n.z.number()}).optional(),clearToolInputs:n.z.boolean().optional(),excludeTools:n.z.array(n.z.string()).optional()}),n.z.object({type:n.z.literal("clear_thinking_20251015"),keep:n.z.union([n.z.literal("all"),n.z.object({type:n.z.literal("thinking_turns"),value:n.z.number()})]).optional()}),n.z.object({type:n.z.literal("compact_20260112"),trigger:n.z.object({type:n.z.literal("input_tokens"),value:n.z.number()}).optional(),pauseAfterCompaction:n.z.boolean().optional(),instructions:n.z.string().optional()})]))}).optional()}),_=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){var o;let n,r=null!=(o=null==(n=null==e?void 0:e.anthropic)?void 0:n.cacheControl)?o:null==n?void 0:n.cache_control;if(r)return t.canCache?(this.breakpointCount++,this.breakpointCount>4)?void this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum 4 cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`}):r:void this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${t.type}. It will be ignored.`})}getWarnings(){return this.warnings}},b=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({model:n.z.string(),maxUses:n.z.number().optional(),maxTokens:n.z.number().int().min(1024).optional(),caching:n.z.object({type:n.z.literal("ephemeral"),ttl:n.z.union([n.z.literal("5m"),n.z.literal("1h")])}).optional()}))),z=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("advisor_result"),text:n.z.string(),stopReason:n.z.string().optional()}),n.z.object({type:n.z.literal("advisor_redacted_result"),encryptedContent:n.z.string(),stopReason:n.z.string().optional()}),n.z.object({type:n.z.literal("advisor_tool_result_error"),errorCode:n.z.string()})]))),w=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({}).strict())),x=(0,o.createProviderExecutedToolFactory)({id:"anthropic.advisor_20260301",inputSchema:w,outputSchema:z,supportsDeferredResults:!0}),S=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({maxCharacters:n.z.number().optional()}))),k=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({command:n.z.enum(["view","create","str_replace","insert"]),path:n.z.string(),file_text:n.z.string().optional(),insert_line:n.z.number().int().optional(),new_str:n.z.string().optional(),insert_text:n.z.string().optional(),old_str:n.z.string().optional(),view_range:n.z.array(n.z.number().int()).optional()}))),I=(0,o.createProviderDefinedToolFactory)({id:"anthropic.text_editor_20250728",inputSchema:k}),T=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({maxUses:n.z.number().optional(),allowedDomains:n.z.array(n.z.string()).optional(),blockedDomains:n.z.array(n.z.string()).optional(),userLocation:n.z.object({type:n.z.literal("approximate"),city:n.z.string().optional(),region:n.z.string().optional(),country:n.z.string().optional(),timezone:n.z.string().optional()}).optional()}))),C=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.array(n.z.object({url:n.z.string(),title:n.z.string().nullable(),pageAge:n.z.string().nullable(),encryptedContent:n.z.string(),type:n.z.literal("web_search_result")})))),E=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({query:n.z.string()}))),M=(0,o.createProviderExecutedToolFactory)({id:"anthropic.web_search_20260209",inputSchema:E,outputSchema:C,supportsDeferredResults:!0}),j=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({maxUses:n.z.number().optional(),allowedDomains:n.z.array(n.z.string()).optional(),blockedDomains:n.z.array(n.z.string()).optional(),userLocation:n.z.object({type:n.z.literal("approximate"),city:n.z.string().optional(),region:n.z.string().optional(),country:n.z.string().optional(),timezone:n.z.string().optional()}).optional()}))),A=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.array(n.z.object({url:n.z.string(),title:n.z.string().nullable(),pageAge:n.z.string().nullable(),encryptedContent:n.z.string(),type:n.z.literal("web_search_result")})))),O=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({query:n.z.string()}))),R=(0,o.createProviderExecutedToolFactory)({id:"anthropic.web_search_20250305",inputSchema:O,outputSchema:A,supportsDeferredResults:!0}),N=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({maxUses:n.z.number().optional(),allowedDomains:n.z.array(n.z.string()).optional(),blockedDomains:n.z.array(n.z.string()).optional(),citations:n.z.object({enabled:n.z.boolean()}).optional(),maxContentTokens:n.z.number().optional()}))),P=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.literal("web_fetch_result"),url:n.z.string(),content:n.z.object({type:n.z.literal("document"),title:n.z.string().nullable(),citations:n.z.object({enabled:n.z.boolean()}).optional(),source:n.z.union([n.z.object({type:n.z.literal("base64"),mediaType:n.z.literal("application/pdf"),data:n.z.string()}),n.z.object({type:n.z.literal("text"),mediaType:n.z.literal("text/plain"),data:n.z.string()})])}),retrievedAt:n.z.string().nullable()}))),$=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({url:n.z.string()}))),q=(0,o.createProviderExecutedToolFactory)({id:"anthropic.web_fetch_20260209",inputSchema:$,outputSchema:P,supportsDeferredResults:!0}),L=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({maxUses:n.z.number().optional(),allowedDomains:n.z.array(n.z.string()).optional(),blockedDomains:n.z.array(n.z.string()).optional(),citations:n.z.object({enabled:n.z.boolean()}).optional(),maxContentTokens:n.z.number().optional()}))),D=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.literal("web_fetch_result"),url:n.z.string(),content:n.z.object({type:n.z.literal("document"),title:n.z.string().nullable(),citations:n.z.object({enabled:n.z.boolean()}).optional(),source:n.z.union([n.z.object({type:n.z.literal("base64"),mediaType:n.z.literal("application/pdf"),data:n.z.string()}),n.z.object({type:n.z.literal("text"),mediaType:n.z.literal("text/plain"),data:n.z.string()})])}),retrievedAt:n.z.string().nullable()}))),U=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({url:n.z.string()}))),F=(0,o.createProviderExecutedToolFactory)({id:"anthropic.web_fetch_20250910",inputSchema:U,outputSchema:D,supportsDeferredResults:!0});async function H({tools:e,toolChoice:n,disableParallelToolUse:r,cacheControlValidator:a,supportsStructuredOutput:i,supportsStrictTools:l,defaultEagerInputStreaming:s=!1}){var u,c;e=(null==e?void 0:e.length)?e:void 0;let d=[],p=new Set,m=a||new _;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:d,betas:p};let h=[];for(let t of e)switch(t.type){case"function":{let e=m.getCacheControl(t.providerOptions,{type:"tool definition",canCache:!0}),o=null==(u=t.providerOptions)?void 0:u.anthropic,n=null!=(c=null==o?void 0:o.eagerInputStreaming)?c:s,r=null==o?void 0:o.deferLoading,a=null==o?void 0:o.allowedCallers;l||null==t.strict||d.push({type:"unsupported",feature:"strict",details:`Tool '${t.name}' has strict: ${t.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),h.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e,...n?{eager_input_streaming:!0}:{},...!0===l&&null!=t.strict?{strict:t.strict}:{},...null!=r?{defer_loading:r}:{},...null!=a?{allowed_callers:a}:{},...null!=t.inputExamples?{input_examples:t.inputExamples.map(e=>e.input)}:{}}),!0===i&&p.add("structured-outputs-2025-11-13"),(null!=t.inputExamples||null!=a)&&p.add("advanced-tool-use-2025-11-20");break}case"provider":switch(t.id){case"anthropic.code_execution_20250522":p.add("code-execution-2025-05-22"),h.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break;case"anthropic.code_execution_20250825":p.add("code-execution-2025-08-25"),h.push({type:"code_execution_20250825",name:"code_execution"});break;case"anthropic.code_execution_20260120":h.push({type:"code_execution_20260120",name:"code_execution"});break;case"anthropic.computer_20250124":p.add("computer-use-2025-01-24"),h.push({name:"computer",type:"computer_20250124",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case"anthropic.computer_20251124":p.add("computer-use-2025-11-24"),h.push({name:"computer",type:"computer_20251124",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,enable_zoom:t.args.enableZoom,cache_control:void 0});break;case"anthropic.computer_20241022":p.add("computer-use-2024-10-22"),h.push({name:"computer",type:"computer_20241022",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case"anthropic.text_editor_20250124":p.add("computer-use-2025-01-24"),h.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break;case"anthropic.text_editor_20241022":p.add("computer-use-2024-10-22"),h.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break;case"anthropic.text_editor_20250429":p.add("computer-use-2025-01-24"),h.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break;case"anthropic.text_editor_20250728":{let e=await (0,o.validateTypes)({value:t.args,schema:S});h.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:e.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":p.add("computer-use-2025-01-24"),h.push({name:"bash",type:"bash_20250124",cache_control:void 0});break;case"anthropic.bash_20241022":p.add("computer-use-2024-10-22"),h.push({name:"bash",type:"bash_20241022",cache_control:void 0});break;case"anthropic.memory_20250818":p.add("context-management-2025-06-27"),h.push({name:"memory",type:"memory_20250818"});break;case"anthropic.web_fetch_20250910":{p.add("web-fetch-2025-09-10");let e=await (0,o.validateTypes)({value:t.args,schema:L});h.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{p.add("code-execution-web-tools-2026-02-09");let e=await (0,o.validateTypes)({value:t.args,schema:N});h.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let e=await (0,o.validateTypes)({value:t.args,schema:j});h.push({type:"web_search_20250305",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{p.add("code-execution-web-tools-2026-02-09");let e=await (0,o.validateTypes)({value:t.args,schema:T});h.push({type:"web_search_20260209",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":h.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break;case"anthropic.tool_search_bm25_20251119":h.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break;case"anthropic.advisor_20260301":{p.add("advisor-tool-2026-03-01");let e=await (0,o.validateTypes)({value:t.args,schema:b});h.push({type:"advisor_20260301",name:"advisor",model:e.model,...void 0!==e.maxUses&&{max_uses:e.maxUses},...void 0!==e.maxTokens&&{max_tokens:e.maxTokens},...void 0!==e.caching&&{caching:e.caching}});break}default:d.push({type:"unsupported",feature:`provider-defined tool ${t.id}`})}break;default:d.push({type:"unsupported",feature:`tool ${t}`})}if(null==n)return{tools:h,toolChoice:r?{type:"auto",disable_parallel_tool_use:r}:void 0,toolWarnings:d,betas:p};let g=n.type;switch(g){case"auto":return{tools:h,toolChoice:{type:"auto",disable_parallel_tool_use:r},toolWarnings:d,betas:p};case"required":return{tools:h,toolChoice:{type:"any",disable_parallel_tool_use:r},toolWarnings:d,betas:p};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:d,betas:p};case"tool":return{tools:h,toolChoice:{type:"tool",name:n.toolName,disable_parallel_tool_use:r},toolWarnings:d,betas:p};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${g}`})}}function B({usage:e,rawUsage:t}){var o,n,r,a,i;let l,s,u=null!=(o=e.cache_creation_input_tokens)?o:0,c=null!=(n=e.cache_read_input_tokens)?n:0,d=null!=(a=null==(r=e.output_tokens_details)?void 0:r.thinking_tokens)?a:void 0,p=null==(i=e.iterations)?void 0:i.some(e=>"fallback_message"===e.type);if(e.iterations&&e.iterations.length>0&&!p){let t=e.iterations.filter(e=>"compaction"===e.type||"message"===e.type);if(t.length>0){let e=t.reduce((e,t)=>({input:e.input+t.input_tokens,output:e.output+t.output_tokens}),{input:0,output:0});l=e.input,s=e.output}else l=e.input_tokens,s=e.output_tokens}else l=e.input_tokens,s=e.output_tokens;return{inputTokens:{total:l+u+c,noCache:l,cacheRead:c,cacheWrite:u},outputTokens:{total:s,text:null==d?void 0:s-d,reasoning:d},raw:null!=t?t:e}}var V=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.literal("code_execution_result"),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}))),J=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({code:n.z.string()}))),W=(0,o.createProviderExecutedToolFactory)({id:"anthropic.code_execution_20250522",inputSchema:J,outputSchema:V}),K=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("code_execution_result"),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("bash_code_execution_result"),content:n.z.array(n.z.object({type:n.z.literal("bash_code_execution_output"),file_id:n.z.string()})),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number()}),n.z.object({type:n.z.literal("bash_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_view_result"),content:n.z.string(),file_type:n.z.string(),num_lines:n.z.number().nullable(),start_line:n.z.number().nullable(),total_lines:n.z.number().nullable()}),n.z.object({type:n.z.literal("text_editor_code_execution_create_result"),is_file_update:n.z.boolean()}),n.z.object({type:n.z.literal("text_editor_code_execution_str_replace_result"),lines:n.z.array(n.z.string()).nullable(),new_lines:n.z.number().nullable(),new_start:n.z.number().nullable(),old_lines:n.z.number().nullable(),old_start:n.z.number().nullable()})]))),G=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("programmatic-tool-call"),code:n.z.string()}),n.z.object({type:n.z.literal("bash_code_execution"),command:n.z.string()}),n.z.discriminatedUnion("command",[n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("view"),path:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("create"),path:n.z.string(),file_text:n.z.string().nullish()}),n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("str_replace"),path:n.z.string(),old_str:n.z.string(),new_str:n.z.string()})])]))),Y=(0,o.createProviderExecutedToolFactory)({id:"anthropic.code_execution_20250825",inputSchema:G,outputSchema:K,supportsDeferredResults:!0}),X=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("code_execution_result"),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("encrypted_code_execution_result"),encrypted_stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number(),content:n.z.array(n.z.object({type:n.z.literal("code_execution_output"),file_id:n.z.string()})).optional().default([])}),n.z.object({type:n.z.literal("bash_code_execution_result"),content:n.z.array(n.z.object({type:n.z.literal("bash_code_execution_output"),file_id:n.z.string()})),stdout:n.z.string(),stderr:n.z.string(),return_code:n.z.number()}),n.z.object({type:n.z.literal("bash_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_tool_result_error"),error_code:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution_view_result"),content:n.z.string(),file_type:n.z.string(),num_lines:n.z.number().nullable(),start_line:n.z.number().nullable(),total_lines:n.z.number().nullable()}),n.z.object({type:n.z.literal("text_editor_code_execution_create_result"),is_file_update:n.z.boolean()}),n.z.object({type:n.z.literal("text_editor_code_execution_str_replace_result"),lines:n.z.array(n.z.string()).nullable(),new_lines:n.z.number().nullable(),new_start:n.z.number().nullable(),old_lines:n.z.number().nullable(),old_start:n.z.number().nullable()})]))),Z=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("programmatic-tool-call"),code:n.z.string()}),n.z.object({type:n.z.literal("bash_code_execution"),command:n.z.string()}),n.z.discriminatedUnion("command",[n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("view"),path:n.z.string()}),n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("create"),path:n.z.string(),file_text:n.z.string().nullish()}),n.z.object({type:n.z.literal("text_editor_code_execution"),command:n.z.literal("str_replace"),path:n.z.string(),old_str:n.z.string(),new_str:n.z.string()})])]))),Q=(0,o.createProviderExecutedToolFactory)({id:"anthropic.code_execution_20260120",inputSchema:Z,outputSchema:X,supportsDeferredResults:!0}),ee=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.array(n.z.object({type:n.z.literal("tool_reference"),toolName:n.z.string()})))),et=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({pattern:n.z.string(),limit:n.z.number().optional()}))),eo=(0,o.createProviderExecutedToolFactory)({id:"anthropic.tool_search_regex_20251119",inputSchema:et,outputSchema:ee,supportsDeferredResults:!0});function en(e){try{if("string"==typeof e)return(0,o.secureJsonParse)(e);if("object"==typeof e&&null!==e)return e}catch(o){let t=null==e?void 0:e.errorCode;return{errorCode:"string"==typeof t?t:"unavailable"}}return{}}async function er({prompt:e,sendReasoning:n,warnings:r,cacheControlValidator:a,toolNameMapping:i}){var l,s,u,c,d,p,m,h,v,b,w,x,S,k,I,T,C,E,M,j,O,R,N,P;let $,q=new Set,L=function(e){let t,o=[];for(let n of e){let{role:e}=n;switch(e){case"system":(null==t?void 0:t.type)!=="system"&&(t={type:"system",messages:[]},o.push(t)),t.messages.push(n);break;case"assistant":(null==t?void 0:t.type)!=="assistant"&&(t={type:"assistant",messages:[]},o.push(t)),t.messages.push(n);break;case"user":case"tool":(null==t?void 0:t.type)!=="user"&&(t={type:"user",messages:[]},o.push(t)),t.messages.push(n);break;default:throw Error(`Unsupported role: ${e}`)}}return o}(e),U=a||new _,F=[];async function H(e){var t,n;let r=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:e,schema:f});return null!=(n=null==(t=null==r?void 0:r.citations)?void 0:t.enabled)&&n}async function B(e){var t;let n=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:e,schema:f});return null!=(t=null==n?void 0:n.containerUpload)&&t}async function J(e){let t=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:e,schema:f});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let e=0;e<L.length;e++){let a=L[e],f=e===L.length-1,_=a.type;switch(_){case"system":{let t=[];for(let{content:e,providerOptions:n}of a.messages){let r=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:n,schema:y}),a=null!=(l=null==r?void 0:r.toolChanges)?l:[],s=[];for(let t of((""!==e||0===a.length&&(null==r?void 0:r.clearAt)==null&&(null==r?void 0:r.effort)==null)&&s.push({type:"text",text:e,cache_control:U.getCacheControl(n,{type:"system message",canCache:!0})}),a))s.push({type:t.type,tool:{type:"tool_reference",name:i.toProviderToolName(t.toolName)}});t.push({content:s,clearAt:null==r?void 0:r.clearAt,effort:null==r?void 0:r.effort,toolChangeCount:a.length})}let n=t.reduce((e,t)=>e+t.toolChangeCount,0),s=t.some(e=>null!=e.clearAt||null!=e.effort);if(0!==e&&(null!=$||0!==n||s))for(let e of(q.add("mid-conversation-system-2026-04-07"),t))F.push({role:"system",content:e.content,...null!=e.clearAt&&{clear_at:e.clearAt},...null!=e.effort&&{output_config:{effort:e.effort}}}),e.toolChangeCount>0&&q.add("mid-conversation-tool-changes-2026-07-01"),null!=e.clearAt&&q.add("mid-conversation-system-clear-at-2026-08-21"),null!=e.effort&&q.add("mid-conversation-effort-2026-08-01");else{for(let e of(n>0&&r.push({type:"other",message:"tool changes on the initial system message are not supported by Anthropic. Configure the initial tool set via the tools option instead. The tool changes have been ignored."}),t))(null!=e.clearAt||null!=e.effort)&&r.push({type:"other",message:"clearAt and effort on the initial system message are not supported by Anthropic. These options have been ignored."});$=t.flatMap(e=>e.content.filter(e=>"text"===e.type))}break}case"user":{let e=[];for(let n of a.messages){let{role:a,content:i}=n;switch(a){case"user":for(let r=0;r<i.length;r++){let a=i[r],l=r===i.length-1,p=null!=(s=U.getCacheControl(a.providerOptions,{type:"user message part",canCache:!0}))?s:l?U.getCacheControl(n.providerOptions,{type:"user message",canCache:!0}):void 0;switch(a.type){case"text":e.push({type:"text",text:a.text,cache_control:p});break;case"file":switch(a.data.type){case"reference":{let t=(0,o.resolveProviderReference)({reference:a.data.reference,provider:"anthropic"});q.add("files-api-2025-04-14"),await B(a.providerOptions)?e.push({type:"container_upload",file_id:t}):"image"===(0,o.getTopLevelMediaType)(a.mediaType)?e.push({type:"image",source:{type:"file",file_id:t},cache_control:p}):e.push({type:"document",source:{type:"file",file_id:t},cache_control:p});break}case"text":{let t=await H(a.providerOptions),o=await J(a.providerOptions);e.push({type:"document",source:{type:"text",media_type:"text/plain",data:a.data.text},title:null!=(u=o.title)?u:a.filename,...o.context&&{context:o.context},...t&&{citations:{enabled:!0}},cache_control:p});break}case"url":case"data":{let n=(0,o.getTopLevelMediaType)(a.mediaType);if("image"===n)e.push({type:"image",source:"url"===a.data.type?{type:"url",url:a.data.url.toString()}:{type:"base64",media_type:(0,o.resolveFullMediaType)({part:a}),data:(0,o.convertToBase64)(a.data.data)},cache_control:p});else if("application"===n&&("url"===a.data.type?"application/pdf"===a.mediaType:"application/pdf"===(0,o.resolveFullMediaType)({part:a}))){q.add("pdfs-2024-09-25");let t=await H(a.providerOptions),n=await J(a.providerOptions);e.push({type:"document",source:"url"===a.data.type?{type:"url",url:a.data.url.toString()}:{type:"base64",media_type:"application/pdf",data:(0,o.convertToBase64)(a.data.data)},title:null!=(c=n.title)?c:a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:p})}else if("text/plain"===a.mediaType){let t=await H(a.providerOptions),n=await J(a.providerOptions);e.push({type:"document",source:"url"===a.data.type?{type:"url",url:a.data.url.toString()}:{type:"text",media_type:"text/plain",data:"string"==typeof(N=a.data.data)?new TextDecoder().decode((0,o.convertBase64ToUint8Array)(N)):new TextDecoder().decode(N)},title:null!=(d=n.title)?d:a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:p})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${a.mediaType}`})}}}}break;case"tool":for(let t=0;t<i.length;t++){let a,l=i[t];if("tool-approval-response"===l.type)continue;let s=l.output,u="providerOptions"in s?s.providerOptions:"content"===s.type?null==(p=s.value.find(e=>null!=e.providerOptions))?void 0:p.providerOptions:void 0,c=t===i.length-1,d=null!=(h=null!=(m=U.getCacheControl(l.providerOptions,{type:"tool result part",canCache:!0}))?m:U.getCacheControl(u,{type:"tool result output",canCache:!0}))?h:c?U.getCacheControl(n.providerOptions,{type:"tool result message",canCache:!0}):void 0;switch(s.type){case"content":a=s.value.map(e=>{var t;switch(e.type){case"text":return{type:"text",text:e.text};case"file":{let t=(0,o.getTopLevelMediaType)(e.mediaType);if("url"===e.data.type){if("image"===t)return{type:"image",source:{type:"url",url:e.data.url.toString()}};return{type:"document",source:{type:"url",url:e.data.url.toString()}}}if("data"===e.data.type){if("image"===t)return{type:"image",source:{type:"base64",media_type:(0,o.resolveFullMediaType)({part:e}),data:(0,o.convertToBase64)(e.data.data)}};if("application/pdf"===(0,o.resolveFullMediaType)({part:e}))return q.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:"application/pdf",data:(0,o.convertToBase64)(e.data.data)}};r.push({type:"other",message:`unsupported tool content part type: ${e.type} with media type: ${e.mediaType}`});return}r.push({type:"other",message:`unsupported tool content part type: ${e.type} with data type: ${e.data.type}`});return}case"custom":{let o=null==(t=e.providerOptions)?void 0:t.anthropic;if((null==o?void 0:o.type)==="tool-reference")return{type:"tool_reference",tool_name:o.toolName};r.push({type:"other",message:"unsupported custom tool content part"});return}default:return void r.push({type:"other",message:`unsupported tool content part type: ${e.type}`})}}).filter(o.isNonNullable);break;case"text":case"error-text":a=s.value;break;case"execution-denied":a=null!=(v=s.reason)?v:"Tool call execution denied.";break;default:a=JSON.stringify(s.value)}e.push({type:"tool_result",tool_use_id:l.toolCallId,content:a,is_error:"error-text"===s.type||"error-json"===s.type||void 0,cache_control:d})}break;default:throw Error(`Unsupported role: ${a}`)}}F.push({role:"user",content:e});break}case"assistant":{let e=[],t=new Set;for(let l=0;l<a.messages.length;l++){let s=a.messages[l],u=l===a.messages.length-1,{content:c}=s;for(let a=0;a<c.length;a++){let l=c[a],d=a===c.length-1,p=null!=(b=U.getCacheControl(l.providerOptions,{type:"assistant message part",canCache:!0}))?b:d?U.getCacheControl(s.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(l.type){case"text":{let t=null==(w=l.providerOptions)?void 0:w.anthropic;(null==t?void 0:t.type)==="compaction"?e.push({type:"compaction",content:l.text,cache_control:p}):e.push({type:"text",text:f&&u&&d?l.text.trim():l.text,...(null==t?void 0:t.citations)!=null&&{citations:t.citations},cache_control:p});break}case"reasoning":if(n){let t=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:l.providerOptions,schema:g});null!=t?null!=t.signature?(U.getCacheControl(l.providerOptions,{type:"thinking block",canCache:!1}),e.push({type:"thinking",thinking:l.text,signature:t.signature})):null!=t.redactedData?(U.getCacheControl(l.providerOptions,{type:"redacted thinking block",canCache:!1}),e.push({type:"redacted_thinking",data:t.redactedData})):r.push({type:"other",message:"unsupported reasoning metadata"}):r.push({type:"other",message:"unsupported reasoning metadata"})}else r.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"tool-call":{let o=ea(l.providerOptions);if(l.providerExecuted){let n=i.toProviderToolName(l.toolName);if((null==(S=null==(x=l.providerOptions)?void 0:x.anthropic)?void 0:S.type)==="mcp-tool-use"){t.add(l.toolCallId);let o=null==(I=null==(k=l.providerOptions)?void 0:k.anthropic)?void 0:I.serverName;if(null==o||"string"!=typeof o){r.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}e.push({type:"mcp_tool_use",id:l.toolCallId,name:l.toolName,input:l.input,server_name:o,cache_control:p})}else if("code_execution"===n&&null!=l.input&&"object"==typeof l.input&&"type"in l.input&&"string"==typeof l.input.type&&("bash_code_execution"===l.input.type||"text_editor_code_execution"===l.input.type)){let{type:t,...n}=l.input;e.push({type:"server_tool_use",id:l.toolCallId,name:t,input:n,...o&&{caller:o},cache_control:p})}else if("code_execution"===n&&null!=l.input&&"object"==typeof l.input&&"type"in l.input&&"programmatic-tool-call"===l.input.type){let{type:t,...n}=l.input;e.push({type:"server_tool_use",id:l.toolCallId,name:"code_execution",input:n,...o&&{caller:o},cache_control:p})}else"code_execution"===n||"web_fetch"===n||"web_search"===n||"tool_search_tool_regex"===n||"tool_search_tool_bm25"===n?e.push({type:"server_tool_use",id:l.toolCallId,name:n,input:l.input,...o&&{caller:o},cache_control:p}):"advisor"===n?e.push({type:"server_tool_use",id:l.toolCallId,name:"advisor",input:{},...o&&{caller:o},cache_control:p}):r.push({type:"other",message:`provider executed tool call for tool ${l.toolName} is not supported`});break}e.push({type:"tool_use",id:l.toolCallId,name:l.toolName,input:"object"!=typeof(P=l.input)||null===P||Array.isArray(P)?{rawInvalidInput:P}:P,...o&&{caller:o},cache_control:p});break}case"tool-result":{let n=i.toProviderToolName(l.toolName),a=ea(l.providerOptions);if(t.has(l.toolCallId)){let t=l.output;if("json"!==t.type&&"error-json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}e.push({type:"mcp_tool_result",tool_use_id:l.toolCallId,is_error:"error-json"===t.type,content:t.value,cache_control:p})}else if("code_execution"===n){let t=l.output;if("error-text"===t.type||"error-json"===t.type){let n={};try{"string"==typeof t.value?n=(0,o.secureJsonParse)(t.value):"object"==typeof t.value&&null!==t.value&&(n=t.value)}catch(e){}"code_execution_tool_result_error"===n.type?e.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:"code_execution_tool_result_error",error_code:null!=(T=n.errorCode)?T:"unknown"},cache_control:p}):e.push({type:"bash_code_execution_tool_result",tool_use_id:l.toolCallId,cache_control:p,content:{type:"bash_code_execution_tool_result_error",error_code:null!=(C=n.errorCode)?C:"unknown"}});break}if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}if(null==t.value||"object"!=typeof t.value||!("type"in t.value)||"string"!=typeof t.value.type){r.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${l.toolName}`});break}if("code_execution_result"===t.value.type){let n=await (0,o.validateTypes)({value:t.value,schema:V});e.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code,content:null!=(E=n.content)?E:[]},cache_control:p})}else if("encrypted_code_execution_result"===t.value.type){let n=await (0,o.validateTypes)({value:t.value,schema:X});"encrypted_code_execution_result"===n.type&&e.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:n.type,encrypted_stdout:n.encrypted_stdout,stderr:n.stderr,return_code:n.return_code,content:null!=(M=n.content)?M:[]},cache_control:p})}else{let n=await (0,o.validateTypes)({value:t.value,schema:K});"code_execution_result"===n.type?e.push({type:"code_execution_tool_result",tool_use_id:l.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code,content:null!=(j=n.content)?j:[]},cache_control:p}):"bash_code_execution_result"===n.type||"bash_code_execution_tool_result_error"===n.type?e.push({type:"bash_code_execution_tool_result",tool_use_id:l.toolCallId,cache_control:p,content:"bash_code_execution_result"===n.type?{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code,content:n.content}:n}):e.push({type:"text_editor_code_execution_tool_result",tool_use_id:l.toolCallId,cache_control:p,content:n})}break}if("web_fetch"===n){let t=l.output;if("error-json"===t.type){e.push({type:"web_fetch_tool_result",tool_use_id:l.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:null!=(O=en(t.value).errorCode)?O:"unavailable"},...a&&{caller:a},cache_control:p});break}if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}let n=await (0,o.validateTypes)({value:t.value,schema:D});e.push({type:"web_fetch_tool_result",tool_use_id:l.toolCallId,content:{type:"web_fetch_result",url:n.url,retrieved_at:n.retrievedAt,content:{type:"document",title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},...a&&{caller:a},cache_control:p});break}if("web_search"===n){let t=l.output;if("error-json"===t.type){e.push({type:"web_search_tool_result",tool_use_id:l.toolCallId,content:{type:"web_search_tool_result_error",error_code:null!=(R=en(t.value).errorCode)?R:"unavailable"},...a&&{caller:a},cache_control:p});break}if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}let n=await (0,o.validateTypes)({value:t.value,schema:A});e.push({type:"web_search_tool_result",tool_use_id:l.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),...a&&{caller:a},cache_control:p});break}if("tool_search_tool_regex"===n||"tool_search_tool_bm25"===n){let t=l.output;if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}let n=(await (0,o.validateTypes)({value:t.value,schema:ee})).map(e=>({type:"tool_reference",tool_name:e.toolName}));e.push({type:"tool_search_tool_result",tool_use_id:l.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:n},cache_control:p});break}if("advisor"===n){let t=l.output;if("json"!==t.type&&"error-json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${l.toolName} is not supported`});break}let n=await (0,o.validateTypes)({value:t.value,schema:z});"advisor_result"===n.type?e.push({type:"advisor_tool_result",tool_use_id:l.toolCallId,content:{type:"advisor_result",text:n.text,...void 0!==n.stopReason&&{stop_reason:n.stopReason}},cache_control:p}):"advisor_redacted_result"===n.type?e.push({type:"advisor_tool_result",tool_use_id:l.toolCallId,content:{type:"advisor_redacted_result",encrypted_content:n.encryptedContent,...void 0!==n.stopReason&&{stop_reason:n.stopReason}},cache_control:p}):e.push({type:"advisor_tool_result",tool_use_id:l.toolCallId,content:{type:"advisor_tool_result_error",error_code:n.errorCode},cache_control:p});break}r.push({type:"other",message:`provider executed tool result for tool ${l.toolName} is not supported`})}}}}F.push({role:"assistant",content:function(e){let t=[],o=[];function n(){t.push(...o.filter(e=>"tool_use"!==e.type),...o.filter(e=>"tool_use"===e.type)),o=[]}for(let r of e)"thinking"===r.type||"redacted_thinking"===r.type?(n(),t.push(r)):o.push(r);return n(),t}(e)});break}default:throw Error(`content type: ${_}`)}}return{prompt:{system:$,messages:F},betas:q}}function ea(e){var t;let o=null==(t=null==e?void 0:e.anthropic)?void 0:t.caller;return((null==o?void 0:o.type)==="code_execution_20250825"||(null==o?void 0:o.type)==="code_execution_20260120")&&o.toolId?{type:o.type,tool_id:o.toolId}:(null==o?void 0:o.type)==="direct"?{type:"direct"}:void 0}function ei({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";default:return"other"}}var el=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),es=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function eu(e){return"boolean"!=typeof e&&(0,o.isRecord)(e)?ec(e):e}function ec(e){var t;let o,n={};if(null!=e.$ref)return{$ref:e.$ref};null!=e.$schema&&(n.$schema=e.$schema),null!=e.$id&&(n.$id=e.$id),null!=e.title&&(n.title=e.title),null!=e.description&&(n.description=e.description),void 0!==e.default&&(n.default=e.default),void 0!==e.const&&(n.const=e.const),null!=e.enum&&(n.enum=e.enum),null!=e.type&&(n.type=e.type),null!=e.anyOf?n.anyOf=e.anyOf.map(eu):null!=e.oneOf&&(n.anyOf=e.oneOf.map(eu)),null!=e.allOf&&(n.allOf=e.allOf.map(eu)),null!=e.definitions&&(n.definitions=Object.fromEntries(Object.entries(e.definitions).map(([e,t])=>[e,eu(t)]))),null!=e.$defs&&(n.$defs=Object.fromEntries(Object.entries(e.$defs).map(([e,t])=>[e,eu(t)]))),("object"===e.type||null!=e.properties)&&(null!=e.properties&&(n.properties=Object.fromEntries(Object.entries(e.properties).map(([e,t])=>[e,eu(t)]))),n.additionalProperties=!1,null!=e.required&&(n.required=e.required)),null!=e.items&&(n.items=Array.isArray(e.items)?e.items.map(eu):eu(e.items)),"string"==typeof e.format&&el.has(e.format)&&(n.format=e.format);let r=(t=e,o=es.flatMap(e=>{var o;let n=t[e];return null==n||!1===n?[]:`${e.replace(/[A-Z]/g,e=>` ${e.toLowerCase()}`)}: ${"string"==typeof(o=n)?o:JSON.stringify(o)}`}),"string"!=typeof t.format||el.has(t.format)||o.push(`format: ${t.format}`),0===o.length?void 0:`${o.join("; ")}.`);return null!=r&&(n.description=null==n.description?r:`${n.description}
|
|
22
26
|
${r}`),n}function ed(e,t,o){var n,r;if("web_search_result_location"===e.type)return{type:"source",sourceType:"url",id:o(),url:e.url,title:null!=(n=e.title)?n:void 0,providerMetadata:{anthropic:{citedText:e.cited_text,encryptedIndex:e.encrypted_index}}};if("page_location"!==e.type&&"char_location"!==e.type)return;let a=t[e.document_index];if(a)return{type:"source",sourceType:"document",id:o(),mediaType:a.mediaType,title:null!=(r=e.document_title)?r:a.title,filename:a.filename,providerMetadata:{anthropic:"page_location"===e.type?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index}}}}function ep(e){return null==e?void 0:{type:e.type,toolId:"tool_id"in e?e.tool_id:void 0}}function em(e){let t=ep(e);return null==t?{}:{providerMetadata:{anthropic:{caller:t}}}}var eh=class e{constructor(e,t){var n;this.specificationVersion="v4",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:o.generateId}static[r.WORKFLOW_SERIALIZE](e){return(0,o.serializeModelOptions)({modelId:e.modelId,config:e.config})}static[r.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,t.config)}supportsUrl(e){return"https:"===e.protocol}get provider(){return this.config.provider}get providerOptionsName(){let e=this.config.provider,t=e.indexOf(".");return -1===t?e:e.substring(0,t)}get supportedUrls(){var e,t,o;return null!=(o=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?o:{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:n,temperature:r,topP:a,topK:i,frequencyPenalty:l,presencePenalty:s,stopSequences:u,responseFormat:c,seed:d,tools:p,toolChoice:m,reasoning:h,providerOptions:g,stream:f}){var y,b,z,w,x,S,k,I,T,C,E,M;let j=[];null!=l&&j.push({type:"unsupported",feature:"frequencyPenalty"}),null!=s&&j.push({type:"unsupported",feature:"presencePenalty"}),null!=d&&j.push({type:"unsupported",feature:"seed"}),null!=r&&r>1?(j.push({type:"unsupported",feature:"temperature",details:`${r} exceeds anthropic maximum of 1.0. clamped to 1.0`}),r=1):null!=r&&r<0&&(j.push({type:"unsupported",feature:"temperature",details:`${r} is below anthropic minimum of 0. clamped to 0`}),r=0),(null==c?void 0:c.type)==="json"&&null==c.schema&&j.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let A=this.providerOptionsName,O=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:g,schema:v}),R="anthropic"!==A?await (0,o.parseProviderOptions)({provider:A,providerOptions:g,schema:v}):null,N=null!=R,P=Object.assign({},null!=O?O:{},null!=R?R:{}),{maxOutputTokens:$,supportsStructuredOutput:q,supportsAdaptiveThinking:L,rejectsSamplingParameters:D,supportsXhighEffort:U,rejectsThinkingDisabledAboveHighEffort:F,isKnownModel:B}=function(e){if(e.includes("claude-opus-5"))return{maxOutputTokens:128e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,isKnownModel:!0};if(e.includes("claude-opus-4-8")||e.includes("claude-opus-4-7")||e.includes("claude-fable-5")||e.includes("claude-sonnet-5"))return{maxOutputTokens:128e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0};if(e.includes("claude-sonnet-4-6")||e.includes("claude-opus-4-6"))return{maxOutputTokens:128e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0};if(e.includes("claude-sonnet-4-5")||e.includes("claude-opus-4-5")||e.includes("claude-haiku-4-5"))return{maxOutputTokens:64e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0};if(e.includes("claude-opus-4-1"))return{maxOutputTokens:32e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0};else if(/claude-sonnet-4(?:-|@)/.test(e))return{maxOutputTokens:64e3,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0};else if(/claude-opus-4(?:-|@)/.test(e))return{maxOutputTokens:32e3,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0};else if(e.includes("claude-3-haiku"))return{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!0};else if(/claude-(?:instant(?:-|$)|v?2(?=$|[-.:])|3(?=$|[-.]))/.test(e))return{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!1};else if(e.includes("claude-"))return{maxOutputTokens:128e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,isKnownModel:!1};else return{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,isKnownModel:!1}}(this.modelId);B||null!=n||j.push({type:"compatibility",feature:"maxOutputTokens",details:`The model "${this.modelId}" is unknown. The max output tokens have been limited to ${$}. Set maxOutputTokens explicitly to override this limit.`}),D&&(null!=r&&(j.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),r=void 0),null!=i&&(j.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),i=void 0),null!=a&&(j.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),a=void 0));let V=B||this.modelId.includes("claude-"),J=(null==(y=this.config.supportsNativeStructuredOutput)||y)&&q,W=(null==(b=this.config.supportsStrictTools)||b)&&q,K=null!=(z=null==P?void 0:P.structuredOutputMode)?z:"auto",G="outputFormat"===K||"auto"===K&&J,Y=(null==c?void 0:c.type)!=="json"||null==c.schema||G?void 0:{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:c.schema};null!=Y&&(null==P?void 0:P.disableParallelToolUse)===!1&&j.push({type:"unsupported",feature:"providerOptions.anthropic.disableParallelToolUse",details:"`disableParallelToolUse: false` is ignored when using the JSON response tool. Parallel tool use is disabled to ensure a single coherent JSON tool call."});let X=null==P?void 0:P.contextManagement,Z=new _,Q=(0,o.createToolNameMapping)({tools:p,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25","anthropic.advisor_20260301":"advisor"}}),{prompt:ee,betas:et}=await er({prompt:t,sendReasoning:null==(w=null==P?void 0:P.sendReasoning)||w,warnings:j,cacheControlValidator:Z,toolNameMapping:Q});if((0,o.isCustomReasoning)(h)&&(null==P?void 0:P.effort)==null){let e=function({reasoning:e,supportsAdaptiveThinking:t,supportsXhighEffort:n,maxOutputTokensForModel:r,warnings:a}){if(!(0,o.isCustomReasoning)(e))return;if("none"===e)return{thinking:{type:"disabled"}};if(t)return{thinking:{type:"adaptive",display:"summarized"},effort:(0,o.mapReasoningToProviderEffort)({reasoning:e,effortMap:{minimal:"low",low:"low",medium:"medium",high:"high",xhigh:n?"xhigh":"max"},warnings:a})};let i=(0,o.mapReasoningToProviderBudget)({reasoning:e,maxOutputTokens:r,maxReasoningBudget:r,warnings:a});if(null!=i)return{thinking:{type:"enabled",budgetTokens:i}}}({reasoning:h,supportsAdaptiveThinking:L,supportsXhighEffort:U,maxOutputTokensForModel:$,warnings:j});null!=e&&(null==P.thinking&&(P.thinking=e.thinking),null!=e.effort&&(null==(x=P.thinking)?void 0:x.type)!=="disabled"&&(P.effort=e.effort))}F&&(null==(S=null==P?void 0:P.thinking)?void 0:S.type)==="disabled"&&("xhigh"===P.effort||"max"===P.effort)&&(j.push({type:"unsupported",feature:"providerOptions.anthropic.effort",details:`effort '${P.effort}' is not supported by ${this.modelId} when thinking is disabled. The effort has been lowered to 'high'.`}),P.effort="high");let eo=null==(k=null==P?void 0:P.thinking)?void 0:k.type,en="enabled"===eo||"adaptive"===eo,ea=(null==P?void 0:P.thinking)!=null&&"blockBinding"in P.thinking?P.thinking.blockBinding:void 0,ei=en||"disabled"===eo||null!=ea,el="enabled"===eo?null==(I=null==P?void 0:P.thinking)?void 0:I.budgetTokens:void 0,es="adaptive"===eo?null==(T=null==P?void 0:P.thinking)?void 0:T.display:void 0,eu=null!=n?n:$,ed={model:this.modelId,max_tokens:eu,temperature:r,top_k:i,top_p:a,stop_sequences:u,...ei&&{thinking:{...null!=eo&&{type:eo},...null!=el&&{budget_tokens:el},...null!=es&&{display:es},...null!=ea&&{block_binding:{prefix_mismatch_behavior:ea.prefixMismatchBehavior}}}},...((null==P?void 0:P.effort)||(null==P?void 0:P.taskBudget)||G&&(null==c?void 0:c.type)==="json"&&null!=c.schema)&&{output_config:{...(null==P?void 0:P.effort)&&{effort:P.effort},...(null==P?void 0:P.taskBudget)&&{task_budget:{type:P.taskBudget.type,total:P.taskBudget.total,...null!=P.taskBudget.remaining&&{remaining:P.taskBudget.remaining}}},...G&&(null==c?void 0:c.type)==="json"&&null!=c.schema&&{format:{type:"json_schema",schema:ec(c.schema)}}}},...(null==P?void 0:P.speed)&&{speed:P.speed},...(null==P?void 0:P.serviceTier)&&{service_tier:P.serviceTier},...(null==P?void 0:P.inferenceGeo)&&{inference_geo:P.inferenceGeo},...(null==P?void 0:P.fallbacks)!=null&&("default"===P.fallbacks||P.fallbacks.length>0)&&{fallbacks:P.fallbacks},...(null==P?void 0:P.cacheControl)&&{cache_control:P.cacheControl},...(null==(C=null==P?void 0:P.metadata)?void 0:C.userId)!=null&&{metadata:{user_id:P.metadata.userId}},...(null==P?void 0:P.mcpServers)&&P.mcpServers.length>0&&{mcp_servers:P.mcpServers.map(e=>({type:e.type,name:e.name,url:e.url,authorization_token:e.authorizationToken,tool_configuration:e.toolConfiguration?{allowed_tools:e.toolConfiguration.allowedTools,enabled:e.toolConfiguration.enabled}:void 0}))},...(null==P?void 0:P.container)&&{container:P.container.skills&&P.container.skills.length>0?{id:P.container.id,skills:P.container.skills.map(e=>({type:e.type,skill_id:"custom"===e.type?(0,o.resolveProviderReference)({reference:e.providerReference,provider:"anthropic"}):e.skillId,version:e.version}))}:P.container.id},system:ee.system,messages:ee.messages,...X&&{context_management:{edits:X.edits.map(e=>{let t=e.type;switch(t){case"clear_tool_uses_20250919":return{type:e.type,...void 0!==e.trigger&&{trigger:e.trigger},...void 0!==e.keep&&{keep:e.keep},...void 0!==e.clearAtLeast&&{clear_at_least:e.clearAtLeast},...void 0!==e.clearToolInputs&&{clear_tool_inputs:e.clearToolInputs},...void 0!==e.excludeTools&&{exclude_tools:e.excludeTools}};case"clear_thinking_20251015":return{type:e.type,...void 0!==e.keep&&{keep:e.keep}};case"compact_20260112":return{type:e.type,...void 0!==e.trigger&&{trigger:e.trigger},...void 0!==e.pauseAfterCompaction&&{pause_after_compaction:e.pauseAfterCompaction},...void 0!==e.instructions&&{instructions:e.instructions}};default:j.push({type:"other",message:`Unknown context management strategy: ${t}`});return}}).filter(e=>void 0!==e)}}};en?("enabled"===eo&&null==el&&(j.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),ed.thinking={type:"enabled",budget_tokens:1024},el=1024),null!=ed.temperature&&(ed.temperature=void 0,j.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),null!=i&&(ed.top_k=void 0,j.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),null!=a&&(ed.top_p=void 0,j.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),ed.max_tokens=eu+(null!=el?el:0)):V&&null!=a&&null!=r&&(j.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),ed.top_p=void 0),B&&ed.max_tokens>$&&(null!=n&&j.push({type:"unsupported",feature:"maxOutputTokens",details:`${ed.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${$} max output tokens. The max output tokens have been limited to ${$}.`}),ed.max_tokens=$),(null==P?void 0:P.mcpServers)&&P.mcpServers.length>0&&et.add("mcp-client-2025-04-04"),X&&(et.add("context-management-2025-06-27"),X.edits.some(e=>"compact_20260112"===e.type)&&et.add("compact-2026-01-12")),(null==P?void 0:P.container)&&P.container.skills&&P.container.skills.length>0&&(et.add("code-execution-2025-08-25"),et.add("skills-2025-10-02"),et.add("files-api-2025-04-14"),(null==p?void 0:p.some(e=>"provider"===e.type&&("anthropic.code_execution_20250825"===e.id||"anthropic.code_execution_20260120"===e.id)))||j.push({type:"other",message:"code execution tool is required when using skills"})),(null==P?void 0:P.taskBudget)&&et.add("task-budgets-2026-03-13"),(null==P?void 0:P.speed)==="fast"&&et.add("fast-mode-2026-02-01"),"updates"===es&&et.add("thinking-display-updates-2026-08-18"),null!=ea&&et.add("thinking-binding-controls-2026-08-01"),(null==P?void 0:P.fallbacks)==="default"?et.add("server-side-fallback-2026-07-01"):(null==P?void 0:P.fallbacks)&&P.fallbacks.length>0&&et.add("server-side-fallback-2026-06-01");let ep=f&&(null==(E=null==P?void 0:P.toolStreaming)||E),{tools:em,toolChoice:eh,toolWarnings:eg,betas:ef}=await H(null!=Y?{tools:[...null!=p?p:[],Y],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:Z,supportsStructuredOutput:!1,supportsStrictTools:W,defaultEagerInputStreaming:ep}:{tools:null!=p?p:[],toolChoice:m,disableParallelToolUse:null==P?void 0:P.disableParallelToolUse,cacheControlValidator:Z,supportsStructuredOutput:J,supportsStrictTools:W,defaultEagerInputStreaming:ep}),ey=Z.getWarnings();return{args:{...ed,tools:em,tool_choice:eh,stream:!0===f||void 0},warnings:[...j,...eg,...ey],betas:new Set([...et,...ef,...e,...null!=(M=null==P?void 0:P.anthropicBeta)?M:[]]),usesJsonResponseTool:null!=Y,toolNameMapping:Q,providerOptionsName:A,usedCustomProviderKey:N}}async getHeaders({betas:e,headers:t}){return(0,o.combineHeaders)(this.config.headers?await (0,o.resolve)(this.config.headers):void 0,t,e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{})}async getBetasFromHeaders(e){var t,n;let r=this.config.headers?await (0,o.resolve)(this.config.headers):void 0,a=null!=(t=null==r?void 0:r["anthropic-beta"])?t:"",i=null!=(n=null==e?void 0:e["anthropic-beta"])?n:"";return new Set([...a.toLowerCase().split(","),...i.toLowerCase().split(",")].map(e=>e.trim()).filter(e=>""!==e))}buildRequestUrl(e){var t,o,n;return null!=(n=null==(o=(t=this.config).buildRequestUrl)?void 0:o.call(t,this.config.baseURL,e))?n:`${this.config.baseURL}/messages`}transformRequestBody(e,t){var o,n,r;return null!=(r=null==(n=(o=this.config).transformRequestBody)?void 0:n.call(o,e,t))?r:e}extractCitationDocuments(e){return e.filter(e=>"user"===e.role).flatMap(e=>e.content).filter(e=>{var t,o;if("file"!==e.type||"application/pdf"!==e.mediaType&&"text/plain"!==e.mediaType)return!1;let n=null==(t=e.providerOptions)?void 0:t.anthropic,r=null==n?void 0:n.citations;return null!=(o=null==r?void 0:r.enabled)&&o}).map(e=>{var t;return{title:null!=(t=e.filename)?t:"Untitled Document",filename:e.filename,mediaType:e.mediaType}})}async doGenerate(e){var t,n,r,a,l,s,u,c,d,p,h,g;let f,y,v,{args:_,warnings:b,betas:z,usesJsonResponseTool:w,toolNameMapping:x,providerOptionsName:S,usedCustomProviderKey:k}=await this.getArgs({...e,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),I=[...this.extractCitationDocuments(e.prompt)],T=eg(_.tools),{responseHeaders:C,value:E,rawValue:M}=await (0,o.postJsonToApi)({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:z,headers:e.headers}),body:this.transformRequestBody(_,z),failedResponseHandler:i,successfulResponseHandler:(0,o.createJsonResponseHandler)(m),abortSignal:e.abortSignal,fetch:this.config.fetch}),j=[],A={},O={},R=!1;for(let e of E.content)switch(e.type){case"text":if(!w){let o=null==(t=e.citations)?void 0:t.filter(e=>"web_search_result_location"===e.type);if(j.push({type:"text",text:e.text,...null!=o&&o.length>0&&{providerMetadata:{anthropic:{citations:o}}}}),e.citations)for(let t of e.citations){let e=ed(t,I,this.generateId);e&&j.push(e)}}break;case"thinking":j.push({type:"reasoning",text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case"redacted_thinking":j.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:e.data}}});break;case"container_upload":j.push({type:"custom",kind:"anthropic.container_upload",providerMetadata:{anthropic:{fileId:e.file_id}}});break;case"compaction":j.push({type:"text",text:e.content,providerMetadata:{anthropic:{type:"compaction"}}});break;case"tool_use":w&&"json"===e.name?(R=!0,j.push({type:"text",text:JSON.stringify(e.input)})):j.push({type:"tool-call",toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),...em(e.caller)});break;case"server_tool_use":if("text_editor_code_execution"===e.name||"bash_code_execution"===e.name)j.push({type:"tool-call",toolCallId:e.id,toolName:x.toCustomToolName("code_execution"),input:JSON.stringify({type:e.name,...e.input}),providerExecuted:!0,...T&&1?{dynamic:!0}:{},...em(e.caller)});else if("web_search"===e.name||"code_execution"===e.name||"web_fetch"===e.name){let t="code_execution"===e.name&&null!=e.input&&"object"==typeof e.input&&"code"in e.input&&!("type"in e.input)?{type:"programmatic-tool-call",...e.input}:e.input;j.push({type:"tool-call",toolCallId:e.id,toolName:x.toCustomToolName(e.name),input:JSON.stringify(t),providerExecuted:!0,...T&&"code_execution"===e.name?{dynamic:!0}:{},...em(e.caller)})}else"tool_search_tool_regex"===e.name||"tool_search_tool_bm25"===e.name?(O[e.id]=e.name,j.push({type:"tool-call",toolCallId:e.id,toolName:x.toCustomToolName(e.name),input:JSON.stringify(e.input),providerExecuted:!0,...em(e.caller)})):"advisor"===e.name&&j.push({type:"tool-call",toolCallId:e.id,toolName:x.toCustomToolName("advisor"),input:JSON.stringify(e.input),providerExecuted:!0,...em(e.caller)});break;case"mcp_tool_use":A[e.id]={type:"tool-call",toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:e.server_name}}},j.push(A[e.id]);break;case"mcp_tool_result":j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:A[e.tool_use_id].toolName,isError:e.is_error,result:e.content,dynamic:!0,providerMetadata:A[e.tool_use_id].providerMetadata});break;case"web_fetch_tool_result":"web_fetch_result"===e.content.type?(I.push({title:null!=(n=e.content.content.title)?n:e.content.url,mediaType:e.content.content.source.media_type}),j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:x.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},...em(e.caller)})):"web_fetch_tool_result_error"===e.content.type&&j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:x.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:e.content.error_code},...em(e.caller)});break;case"web_search_tool_result":if(Array.isArray(e.content))for(let t of(j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:x.toCustomToolName("web_search"),result:e.content.map(e=>{var t;return{url:e.url,...null!=e.title?{title:e.title}:{},pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}}),...em(e.caller)}),e.content))j.push({type:"source",sourceType:"url",id:this.generateId(),url:t.url,...null!=t.title?{title:t.title}:{},providerMetadata:{anthropic:{pageAge:null!=(r=t.page_age)?r:null}}});else j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:x.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code},...em(e.caller)});break;case"code_execution_tool_result":"code_execution_result"===e.content.type?j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:x.toCustomToolName("code_execution"),result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(a=e.content.content)?a:[]}}):"encrypted_code_execution_result"===e.content.type?j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:x.toCustomToolName("code_execution"),result:{type:e.content.type,encrypted_stdout:e.content.encrypted_stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(l=e.content.content)?l:[]}}):"code_execution_tool_result_error"===e.content.type&&j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:x.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code}});break;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:x.toCustomToolName("code_execution"),result:e.content});break;case"tool_search_tool_result":{let t=O[e.tool_use_id];if(null==t){let e=x.toCustomToolName("tool_search_tool_bm25");x.toCustomToolName("tool_search_tool_regex"),t="tool_search_tool_bm25"!==e?"tool_search_tool_bm25":"tool_search_tool_regex"}"tool_search_tool_search_result"===e.content.type?j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:x.toCustomToolName(t),result:e.content.tool_references.map(e=>({type:e.type,toolName:e.tool_name}))}):j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:x.toCustomToolName(t),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:e.content.error_code}});break}case"advisor_tool_result":{let t=x.toCustomToolName("advisor");"advisor_result"===e.content.type?j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:t,result:{type:"advisor_result",text:e.content.text,...null!=e.content.stop_reason&&{stopReason:e.content.stop_reason}}}):"advisor_redacted_result"===e.content.type?j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:t,result:{type:"advisor_redacted_result",encryptedContent:e.content.encrypted_content,...null!=e.content.stop_reason&&{stopReason:e.content.stop_reason}}}):j.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:t,isError:!0,result:{type:"advisor_tool_result_error",errorCode:e.content.error_code}})}}return{content:j,finishReason:{unified:ei({finishReason:E.stop_reason,isJsonResponseFromTool:R}),raw:null!=(s=E.stop_reason)?s:void 0},usage:B({usage:E.usage}),request:{body:_},response:{id:null!=(u=E.id)?u:void 0,modelId:null!=(c=E.model)?c:void 0,headers:C,body:M},warnings:b,providerMetadata:(f=ey(E.stop_details),v={anthropic:y={usage:E.usage,stopSequence:null!=(d=E.stop_sequence)?d:null,...null!=f?{stopDetails:f}:{},iterations:E.usage.iterations?E.usage.iterations.map(e=>({type:e.type,...null!=e.model?{model:e.model}:{},inputTokens:e.input_tokens,outputTokens:e.output_tokens,...e.cache_creation_input_tokens?{cacheCreationInputTokens:e.cache_creation_input_tokens}:{},...e.cache_read_input_tokens?{cacheReadInputTokens:e.cache_read_input_tokens}:{}})):null,container:E.container?{expiresAt:E.container.expires_at,id:E.container.id,skills:null!=(h=null==(p=E.container.skills)?void 0:p.map(e=>({type:e.type,skillId:e.skill_id,version:e.version})))?h:null}:null,contextManagement:null!=(g=ef(E.context_management))?g:null}},k&&"anthropic"!==S&&(v[S]=y),v)}}async doStream(e){var n,r,a,l;let s,u,c,d,{args:p,warnings:m,betas:g,usesJsonResponseTool:f,toolNameMapping:y,providerOptionsName:v,usedCustomProviderKey:_}=await this.getArgs({...e,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),b=[...this.extractCitationDocuments(e.prompt)],z=eg(p.tools),w=this.buildRequestUrl(!0),{responseHeaders:x,value:S}=await (0,o.postJsonToApi)({url:w,headers:await this.getHeaders({betas:g,headers:e.headers}),body:this.transformRequestBody(p,g),failedResponseHandler:i,successfulResponseHandler:(0,o.createEventSourceResponseHandler)(h),abortSignal:e.abortSignal,fetch:this.config.fetch}),k={unified:"other",raw:void 0},I={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},T={},C={},E={},M=null,j=null,A=null,O=!1,R=!1,N=!1,P=this.generateId,[$,q]=S.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:m})},transform(n,r){var a,i,l,p,m,h,g,w,x,S,$,q,L,D,U,F,H;if(N)return;if(e.includeRawChunks&&r.enqueue({type:"raw",rawValue:n.rawValue}),!n.success)return void r.enqueue({type:"error",error:n.error});let V=n.value;switch(V.type){case"ping":return;case"content_block_start":{let e=V.content_block,t=e.type;if("fallback"===t)return;switch(d=t,t){case"text":if(f)return;T[V.index]={type:"text",citations:[]},r.enqueue({type:"text-start",id:String(V.index)});return;case"thinking":T[V.index]={type:"reasoning"},r.enqueue({type:"reasoning-start",id:String(V.index)});return;case"redacted_thinking":T[V.index]={type:"reasoning"},r.enqueue({type:"reasoning-start",id:String(V.index),providerMetadata:{anthropic:{redactedData:e.data}}});return;case"compaction":T[V.index]={type:"text",citations:[]},r.enqueue({type:"text-start",id:String(V.index),providerMetadata:{anthropic:{type:"compaction"}}});return;case"tool_use":if(f&&"json"===e.name)O=!0,T[V.index]={type:"text",citations:[]},r.enqueue({type:"text-start",id:String(V.index)});else{let t=ep(e.caller),o=e.input&&Object.keys(e.input).length>0?JSON.stringify(e.input):"";T[V.index]={type:"tool-call",toolCallId:e.id,toolName:e.name,input:o,firstDelta:0===o.length,...t&&{caller:t}},r.enqueue({type:"tool-input-start",id:e.id,toolName:e.name})}return;case"server_tool_use":{let t=ep(e.caller);if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(e.name)){let o="text_editor_code_execution"===e.name||"bash_code_execution"===e.name?"code_execution":e.name,n="text_editor_code_execution"===e.name||"bash_code_execution"===e.name?e.name:"code_execution"===e.name?"programmatic-tool-call":void 0,a=y.toCustomToolName(o),i=null!=e.input&&"object"==typeof e.input&&Object.keys(e.input).length>0?JSON.stringify(e.input):"";T[V.index]={type:"tool-call",toolCallId:e.id,toolName:a,input:i,providerExecuted:!0,...z&&"code_execution"===o?{dynamic:!0}:{},firstDelta:0===i.length,providerToolName:o,providerToolInputType:n,...t&&{caller:t}},r.enqueue({type:"tool-input-start",id:e.id,toolName:a,providerExecuted:!0,...z&&"code_execution"===o?{dynamic:!0}:{}})}else if("tool_search_tool_regex"===e.name||"tool_search_tool_bm25"===e.name){E[e.id]=e.name;let o=y.toCustomToolName(e.name);T[V.index]={type:"tool-call",toolCallId:e.id,toolName:o,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:e.name,...t&&{caller:t}},r.enqueue({type:"tool-input-start",id:e.id,toolName:o,providerExecuted:!0})}else if("advisor"===e.name){let o=y.toCustomToolName("advisor");T[V.index]={type:"tool-call",toolCallId:e.id,toolName:o,input:"{}",providerExecuted:!0,firstDelta:!0,providerToolName:e.name,...t&&{caller:t}},r.enqueue({type:"tool-input-start",id:e.id,toolName:o,providerExecuted:!0})}return}case"web_fetch_tool_result":"web_fetch_result"===e.content.type?(b.push({title:null!=(a=e.content.content.title)?a:e.content.url,mediaType:e.content.content.source.media_type}),r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:y.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},...em(e.caller)})):"web_fetch_tool_result_error"===e.content.type&&r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:y.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:e.content.error_code},...em(e.caller)});return;case"web_search_tool_result":if(Array.isArray(e.content))for(let t of(r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:y.toCustomToolName("web_search"),result:e.content.map(e=>{var t;return{url:e.url,...null!=e.title?{title:e.title}:{},pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}}),...em(e.caller)}),e.content))r.enqueue({type:"source",sourceType:"url",id:P(),url:t.url,...null!=t.title?{title:t.title}:{},providerMetadata:{anthropic:{pageAge:null!=(i=t.page_age)?i:null}}});else r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:y.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code},...em(e.caller)});return;case"code_execution_tool_result":"code_execution_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:y.toCustomToolName("code_execution"),result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(l=e.content.content)?l:[]}}):"encrypted_code_execution_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:y.toCustomToolName("code_execution"),result:{type:e.content.type,encrypted_stdout:e.content.encrypted_stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(p=e.content.content)?p:[]}}):"code_execution_tool_result_error"===e.content.type&&r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:y.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code}});return;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":return void r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:y.toCustomToolName("code_execution"),result:e.content});case"tool_search_tool_result":{let t=E[e.tool_use_id];if(null==t){let e=y.toCustomToolName("tool_search_tool_bm25");y.toCustomToolName("tool_search_tool_regex"),t="tool_search_tool_bm25"!==e?"tool_search_tool_bm25":"tool_search_tool_regex"}"tool_search_tool_search_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:y.toCustomToolName(t),result:e.content.tool_references.map(e=>({type:e.type,toolName:e.tool_name}))}):r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:y.toCustomToolName(t),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:e.content.error_code}});return}case"advisor_tool_result":{let t=y.toCustomToolName("advisor");"advisor_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:t,result:{type:"advisor_result",text:e.content.text,...null!=e.content.stop_reason&&{stopReason:e.content.stop_reason}}}):"advisor_redacted_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:t,result:{type:"advisor_redacted_result",encryptedContent:e.content.encrypted_content,...null!=e.content.stop_reason&&{stopReason:e.content.stop_reason}}}):r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:t,isError:!0,result:{type:"advisor_tool_result_error",errorCode:e.content.error_code}});return}case"mcp_tool_use":C[e.id]={type:"tool-call",toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:e.server_name}}},r.enqueue(C[e.id]);return;case"mcp_tool_result":return void r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:C[e.tool_use_id].toolName,isError:e.is_error,result:e.content,dynamic:!0,providerMetadata:C[e.tool_use_id].providerMetadata});default:throw Error(`Unsupported content block type: ${t}`)}}case"content_block_stop":if(null!=T[V.index]){let e=T[V.index];switch(e.type){case"text":r.enqueue({type:"text-end",id:String(V.index),...e.citations.length>0&&{providerMetadata:{anthropic:{citations:e.citations}}}});break;case"reasoning":r.enqueue({type:"reasoning-end",id:String(V.index)});break;case"tool-call":if(!(f&&"json"===e.toolName)){r.enqueue({type:"tool-input-end",id:e.toolCallId});let t=""===e.input?"{}":e.input;if("code_execution"===e.providerToolName)try{let e=(0,o.secureJsonParse)(t);null!=e&&"object"==typeof e&&"code"in e&&!("type"in e)&&(t=JSON.stringify({type:"programmatic-tool-call",...e}))}catch(e){}r.enqueue({type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t,providerExecuted:e.providerExecuted,...z&&"code_execution"===e.providerToolName?{dynamic:!0}:{},...e.caller&&{providerMetadata:{anthropic:{caller:e.caller}}}})}}delete T[V.index]}d=void 0;return;case"content_block_delta":{let e=V.delta.type;switch(e){case"text_delta":if(f)return;r.enqueue({type:"text-delta",id:String(V.index),delta:V.delta.text});return;case"thinking_delta":return void r.enqueue({type:"reasoning-delta",id:String(V.index),delta:V.delta.thinking});case"signature_delta":"thinking"===d&&r.enqueue({type:"reasoning-delta",id:String(V.index),delta:"",providerMetadata:{anthropic:{signature:V.delta.signature}}});return;case"compaction_delta":null!=V.delta.content&&r.enqueue({type:"text-delta",id:String(V.index),delta:V.delta.content});return;case"input_json_delta":{let e=T[V.index],t=V.delta.partial_json;if(0===t.length)return;if(O){if((null==e?void 0:e.type)!=="text")return;r.enqueue({type:"text-delta",id:String(V.index),delta:t})}else{if((null==e?void 0:e.type)!=="tool-call")return;e.firstDelta&&null!=e.providerToolInputType&&(t=`{"type": "${e.providerToolInputType}",${t.substring(1)}`),r.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:t}),e.input+=t,e.firstDelta=!1}return}case"citations_delta":{let e=V.delta.citation,t=T[V.index];(null==t?void 0:t.type)==="text"&&"web_search_result_location"===e.type&&t.citations.push(e);let o=ed(e,b,P);o&&r.enqueue(o);return}default:throw Error(`Unsupported delta type: ${e}`)}}case"message_start":if(R){if(s===V.message.id)return;N=!0,r.enqueue({type:"error",error:new t.InvalidResponseDataError({data:V,message:`Received message_start for message ${JSON.stringify(V.message.id)} while message ${JSON.stringify(s)} is still open.`})});return}if(R=!0,s=V.message.id,I.input_tokens=V.message.usage.input_tokens,I.cache_read_input_tokens=null!=(m=V.message.usage.cache_read_input_tokens)?m:0,I.cache_creation_input_tokens=null!=(h=V.message.usage.cache_creation_input_tokens)?h:0,u={...V.message.usage},null!=V.message.container&&(A={expiresAt:V.message.container.expires_at,id:V.message.container.id,skills:null}),null!=V.message.stop_reason&&(k={unified:ei({finishReason:V.message.stop_reason,isJsonResponseFromTool:O}),raw:V.message.stop_reason}),r.enqueue({type:"response-metadata",id:null!=(g=V.message.id)?g:void 0,modelId:null!=(w=V.message.model)?w:void 0}),null!=V.message.content)for(let e=0;e<V.message.content.length;e++){let t=V.message.content[e];if("tool_use"===t.type){let e=ep(t.caller);r.enqueue({type:"tool-input-start",id:t.id,toolName:t.name});let o=JSON.stringify(null!=(x=t.input)?x:{});r.enqueue({type:"tool-input-delta",id:t.id,delta:o}),r.enqueue({type:"tool-input-end",id:t.id}),r.enqueue({type:"tool-call",toolCallId:t.id,toolName:t.name,input:o,...e&&{providerMetadata:{anthropic:{caller:e}}}})}}return;case"message_delta":null!=V.usage.input_tokens&&I.input_tokens!==V.usage.input_tokens&&(I.input_tokens=V.usage.input_tokens),I.output_tokens=V.usage.output_tokens,null!=V.usage.output_tokens_details&&(I.output_tokens_details=V.usage.output_tokens_details),null!=V.usage.cache_read_input_tokens&&(I.cache_read_input_tokens=V.usage.cache_read_input_tokens),null!=V.usage.cache_creation_input_tokens&&(I.cache_creation_input_tokens=V.usage.cache_creation_input_tokens),null!=V.usage.iterations&&(I.iterations=V.usage.iterations),k={unified:ei({finishReason:V.delta.stop_reason,isJsonResponseFromTool:O}),raw:null!=(S=V.delta.stop_reason)?S:void 0},j=null!=($=V.delta.stop_sequence)?$:null,c=ey(V.delta.stop_details),A=null!=V.delta.container?{expiresAt:V.delta.container.expires_at,id:V.delta.container.id,skills:null!=(L=null==(q=V.delta.container.skills)?void 0:q.map(e=>({type:e.type,skillId:e.skill_id,version:e.version})))?L:null}:null,V.context_management&&(M=ef(V.context_management)),u={...u,...V.usage};return;case"message_stop":{R=!1,s=void 0;let e={usage:null!=u?u:null,stopSequence:j,...null!=c?{stopDetails:c}:{},iterations:I.iterations?I.iterations.map(e=>({type:e.type,...null!=e.model?{model:e.model}:{},inputTokens:e.input_tokens,outputTokens:e.output_tokens,...e.cache_creation_input_tokens?{cacheCreationInputTokens:e.cache_creation_input_tokens}:{},...e.cache_read_input_tokens?{cacheReadInputTokens:e.cache_read_input_tokens}:{}})):null,container:A,contextManagement:M},t={anthropic:e};_&&"anthropic"!==v&&(t[v]=e),r.enqueue({type:"finish",finishReason:k,usage:B({usage:I,rawUsage:u}),providerMetadata:t});return}case"error":let J;return void r.enqueue({type:"error",error:(J=function(e){switch(e){case"api_error":return{statusCode:500,isRetryable:!0};case"overloaded_error":return{statusCode:529,isRetryable:!0};case"rate_limit_error":return{statusCode:429,isRetryable:!0};case"request_too_large":return{statusCode:413,isRetryable:!1};case"authentication_error":return{statusCode:401,isRetryable:!1};case"permission_error":return{statusCode:403,isRetryable:!1};case"not_found_error":return{statusCode:404,isRetryable:!1};case"billing_error":case"invalid_request_error":return{statusCode:400,isRetryable:!1};default:return{}}}((D=V.error).type),(0,o.createProviderStreamError)({message:D.message,type:D.type,code:null!=(U=D.code)?U:void 0,statusCode:null!=(F=D.statusCode)?F:J.statusCode,isRetryable:null!=(H=D.isRetryable)?H:J.isRetryable,data:"data"in D?D.data:D}))});default:throw Error(`Unsupported chunk type: ${V}`)}}})).tee(),L=$.getReader();try{await L.read();let e=await L.read();if((null==(n=e.value)?void 0:n.type)==="raw"&&(e=await L.read()),(null==(r=e.value)?void 0:r.type)==="error"){let n=e.value.error;if(!(0,o.isProviderStreamError)(n))throw Error("Expected a normalized Anthropic stream error");throw new t.APICallError({message:n.message,url:w,requestBodyValues:p,statusCode:null!=(a=n.statusCode)?a:500,responseHeaders:x,responseBody:JSON.stringify(n.data),isRetryable:null!=(l=n.isRetryable)&&l})}}finally{L.cancel().catch(()=>{}),L.releaseLock()}return{stream:q,request:{body:p},response:{headers:x}}}};function eg(e){if(!e)return!1;let t=!1,o=!1;for(let n of e){if("type"in n&&("web_fetch_20260209"===n.type||"web_search_20260209"===n.type)){t=!0;continue}if("type"in n&&("code_execution_20250522"===n.type||"code_execution_20250825"===n.type||"code_execution_20260120"===n.type)){o=!0;break}}return t&&!o}function ef(e){return e?{appliedEdits:e.applied_edits.map(e=>{switch(e.type){case"clear_tool_uses_20250919":return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case"clear_thinking_20251015":return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens};case"compact_20260112":return{type:e.type}}}).filter(e=>void 0!==e)}:null}function ey(e){if(null!=e)return{type:e.type,...null!=e.category?{category:e.category}:{},...null!=e.explanation?{explanation:e.explanation}:{},...null!=e.recommended_model?{recommendedModel:e.recommended_model}:{}}}var ev=/^[A-Za-z0-9_-]{1,64}$/,e_=v.pick({anthropicBeta:!0}),eb=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({id:n.z.string(),type:n.z.literal("message_batch"),processing_status:n.z.string(),request_counts:n.z.object({processing:n.z.number(),succeeded:n.z.number(),errored:n.z.number(),canceled:n.z.number(),expired:n.z.number()}),created_at:n.z.string(),expires_at:n.z.string(),archived_at:n.z.string().nullish(),cancel_initiated_at:n.z.string().nullish(),ended_at:n.z.string().nullish(),results_url:n.z.string().nullish()}))),ez=new Set(["advisor_tool_result","bash_code_execution_tool_result","code_execution_tool_result","compaction","container_upload","fallback","mcp_tool_result","mcp_tool_use","redacted_thinking","server_tool_use","text","text_editor_code_execution_tool_result","thinking","tool_search_tool_result","tool_use","web_fetch_tool_result","web_search_tool_result"]),ew=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("type",[n.z.object({type:n.z.literal("succeeded"),message:n.z.unknown()}),n.z.object({type:n.z.literal("errored"),error:n.z.object({type:n.z.literal("error"),error:n.z.object({type:n.z.string(),message:n.z.string()}),request_id:n.z.string().nullish()})}),n.z.object({type:n.z.literal("canceled")}),n.z.object({type:n.z.literal("expired")})]))),ex=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({custom_id:n.z.string(),result:n.z.unknown()}))),eS=class e extends eh{static[r.WORKFLOW_SERIALIZE](e){return eh[r.WORKFLOW_SERIALIZE](e)}static[r.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,t.config)}constructor(e,t){super(e,t)}async experimental_doStartBatch({requests:e,providerOptions:n,headers:r,abortSignal:a,webhookUrl:l}){var s,u=e;let c=new Set;for(let e of u){if(!ev.test(e.id))throw new t.InvalidArgumentError({argument:"requests",message:`Anthropic batch request ID "${e.id}" must match ^[A-Za-z0-9_-]{1,64}$.`});if(c.has(e.id))throw new t.InvalidArgumentError({argument:"requests",message:`Anthropic batch request IDs must be unique; duplicate ID "${e.id}".`});c.add(e.id)}let d=new Set(await ek({provider:this.config.provider,providerOptions:n})),p=new Set(d),m=[],h=null==l?[]:[{warning:{type:"unsupported",feature:"webhookUrl",details:"The Anthropic Message Batches API does not support completion webhooks."}}];for(let o of e){if((await ek({provider:this.config.provider,providerOptions:o.options.providerOptions})).length>0)throw new t.UnsupportedFunctionalityError({functionality:"per-request providerOptions.anthropic.anthropicBeta",message:`Anthropic Message Batches do not support per-request betas (request "${o.id}"). Set providerOptions.anthropic.anthropicBeta on startTextBatch instead.`});let e=await this.getArgs({...o.options,stream:!1,userSuppliedBetas:new Set(d)});if(e.usesJsonResponseTool)throw new t.UnsupportedFunctionalityError({functionality:"batch responseFormat JSON-tool fallback",message:`Anthropic Message Batches cannot decode the JSON-tool structured-output fallback (request "${o.id}") because batch results are retrieved independently of the start call. Use a model that supports native output_format structured outputs.`});let n=null==(s=o.options.tools)?void 0:s.find(t=>"provider"===t.type&&e.toolNameMapping.toProviderToolName(t.name)!==t.name);if(null!=n)throw new t.UnsupportedFunctionalityError({functionality:"aliased provider tool names in batches",message:`Anthropic Message Batches cannot restore the custom provider-tool name "${n.name}" when results are retrieved independently of the start call (request "${o.id}"). Use the provider's canonical tool name.`});let r=this.transformRequestBody(e.args,e.betas);for(let n of(function({body:e,requestId:o}){if(null!=e.speed)throw new t.UnsupportedFunctionalityError({functionality:"providerOptions.anthropic.speed",message:`Anthropic Message Batches do not support speed (request "${o}").`});if(Array.isArray(e.fallbacks)&&e.fallbacks.some(e=>null!=e&&"object"==typeof e&&"speed"in e&&null!=e.speed))throw new t.UnsupportedFunctionalityError({functionality:"providerOptions.anthropic.fallbacks[].speed",message:`Anthropic Message Batches do not support fallback speed (request "${o}").`})}({body:r,requestId:o.id}),m.push({custom_id:o.id,params:r}),e.betas))p.add(n);for(let t of e.warnings)h.push({requestId:o.id,warning:t})}let{value:g}=await (0,o.postJsonToApi)({url:this.getBatchUrl(""),headers:await this.getStartBatchHeaders({betas:p,headers:r}),body:{requests:m},failedResponseHandler:i,successfulResponseHandler:(0,o.createJsonResponseHandler)(eb),abortSignal:a,fetch:this.config.fetch});return{batchId:g.id,...eI(g),warnings:h}}async experimental_doGetBatchStatus(e){return eI(await this.retrieveBatch(e))}async experimental_doGetBatchResults(e){let n=await this.retrieveBatch(e);if("pending"===eI(n).status)throw new t.InvalidArgumentError({argument:"batchId",message:`Anthropic batch "${e.batchId}" is not complete.`});if(null!=n.archived_at)throw new t.InvalidArgumentError({argument:"batchId",message:`Anthropic batch "${e.batchId}" results are no longer available.`});if(null==n.results_url)throw new t.InvalidResponseDataError({data:n,message:`Anthropic batch "${e.batchId}" completed without batch output.`});let{value:r}=await (0,o.getFromApi)({url:n.results_url,validateUrl:!0,credentialedOrigin:this.config.baseURL,trustedOrigin:this.config.baseURL,headers:await this.getBatchHeaders(e.headers),failedResponseHandler:i,successfulResponseHandler:(0,o.createJsonLinesResponseHandler)(ex),abortSignal:e.abortSignal,fetch:this.config.fetch});return(0,o.convertAsyncIteratorToReadableStream)(this.iterateBatchResults(r))}async retrieveBatch(e){let{value:t}=await (0,o.getFromApi)({url:this.getBatchUrl(`/${encodeURIComponent(e.batchId)}`),validateUrl:!1,headers:await this.getBatchHeaders(e.headers),failedResponseHandler:i,successfulResponseHandler:(0,o.createJsonResponseHandler)(eb),abortSignal:e.abortSignal,fetch:this.config.fetch});return t}async *iterateBatchResults(e){for await(let t of e)yield await eT(t,this.generateId)}getBatchUrl(e){return`${this.config.baseURL}/messages/batches${e}`}async getStartBatchHeaders({betas:e,headers:t}){return(0,o.combineHeaders)((0,o.normalizeHeaders)(await this.getBatchHeaders(t)),{"anthropic-beta":e.size>0?Array.from(e).join(","):void 0})}async getBatchHeaders(e){return(0,o.combineHeaders)(this.config.headers?await (0,o.resolve)(this.config.headers):void 0,e)}};async function ek({provider:e,providerOptions:t}){var n;let r=e.split(".")[0],a=await (0,o.parseProviderOptions)({provider:"anthropic",providerOptions:t,schema:e_}),i="anthropic"!==r?await (0,o.parseProviderOptions)({provider:r,providerOptions:t,schema:e_}):void 0;return null!=(n=Object.assign({},null!=a?a:{},null!=i?i:{}).anthropicBeta)?n:[]}function eI(e){var t,n,r,a,i;let l=(i=e.request_counts,(0,o.normalizeBatchRequestCounts)({total:i.processing+i.succeeded+i.errored+i.canceled+i.expired,pending:i.processing,completed:i.succeeded,failed:i.errored+i.canceled+i.expired}));return{status:"ended"===e.processing_status?"completed":"pending",rawStatus:e.processing_status,...null!=l?{requestCounts:l}:{},createdAt:e.created_at,expiresAt:e.expires_at,providerMetadata:{anthropic:{archivedAt:null!=(t=e.archived_at)?t:null,cancelInitiatedAt:null!=(n=e.cancel_initiated_at)?n:null,endedAt:null!=(r=e.ended_at)?r:null,requestCounts:e.request_counts,resultsUrl:null!=(a=e.results_url)?a:null}}}}async function eT(e,t){let n=await (0,o.safeValidateTypes)({value:e.result,schema:ew});if(!n.success)return eC(e.custom_id);let r=n.value;switch(r.type){case"canceled":return{id:e.custom_id,status:"cancelled"};case"expired":return{id:e.custom_id,status:"expired"};case"errored":{let t=r.error.request_id;return{id:e.custom_id,status:"failed",error:{message:r.error.error.message,type:r.error.error.type},...null!=t?{providerMetadata:{anthropic:{requestId:t}}}:{}}}case"succeeded":{let o=await eE(r.message);if(null==o)return eC(e.custom_id);return{id:e.custom_id,status:"succeeded",result:function(e,t){var o,n,r,a,i,l,s,u,c,d,p,m,h;let g,f=[],y={},v={};for(let l of e.content)switch(l.type){case"text":let e=l.citations;for(let n of(f.push({type:"text",text:l.text,...null!=e&&e.length>0&&{providerMetadata:{anthropic:{citations:e}}}}),null!=(o=l.citations)?o:[])){let e=ed(n,[],t);null!=e&&f.push(e)}break;case"thinking":f.push({type:"reasoning",text:l.thinking,providerMetadata:{anthropic:{signature:l.signature}}});break;case"redacted_thinking":f.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:l.data}}});break;case"container_upload":f.push({type:"custom",kind:"anthropic.container_upload",providerMetadata:{anthropic:{fileId:l.file_id}}});break;case"compaction":f.push({type:"text",text:l.content,providerMetadata:{anthropic:{type:"compaction"}}});break;case"tool_use":f.push({type:"tool-call",toolCallId:l.id,toolName:l.name,input:JSON.stringify(l.input),...eM(l.caller)});break;case"server_tool_use":{let e="bash_code_execution"===l.name||"text_editor_code_execution"===l.name,t=e||"code_execution"===l.name,o=e?"code_execution":l.name;("tool_search_tool_bm25"===l.name||"tool_search_tool_regex"===l.name)&&(v[l.id]=l.name),f.push({type:"tool-call",toolCallId:l.id,toolName:o,input:JSON.stringify(e?{type:l.name,...null!=(n=l.input)?n:{}}:"code_execution"===l.name&&null!=l.input&&"code"in l.input&&!("type"in l.input)?{type:"programmatic-tool-call",...l.input}:l.input),providerExecuted:!0,...t?{dynamic:!0}:{},...eM(l.caller)});break}case"mcp_tool_use":{let e={type:"tool-call",toolCallId:l.id,toolName:l.name,input:JSON.stringify(l.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{serverName:l.server_name,type:"mcp-tool-use"}}};y[l.id]=e,f.push(e);break}case"mcp_tool_result":{let e=y[l.tool_use_id];f.push({type:"tool-result",toolCallId:l.tool_use_id,toolName:null!=(r=null==e?void 0:e.toolName)?r:"mcp",isError:l.is_error,result:l.content,dynamic:!0,...(null==e?void 0:e.providerMetadata)!=null&&{providerMetadata:e.providerMetadata}});break}case"web_fetch_tool_result":f.push({type:"tool-result",toolCallId:l.tool_use_id,toolName:"web_fetch",..."web_fetch_tool_result_error"===l.content.type?{isError:!0,result:{errorCode:l.content.error_code,type:l.content.type}}:{result:{content:{citations:l.content.content.citations,source:{data:l.content.content.source.data,mediaType:l.content.content.source.media_type,type:l.content.content.source.type},title:l.content.content.title,type:l.content.content.type},retrievedAt:l.content.retrieved_at,type:l.content.type,url:l.content.url}},...eM(l.caller)});break;case"web_search_tool_result":if(f.push({type:"tool-result",toolCallId:l.tool_use_id,toolName:"web_search",...Array.isArray(l.content)?{result:l.content.map(e=>{var t;return{encryptedContent:e.encrypted_content,pageAge:null!=(t=e.page_age)?t:null,...null!=e.title?{title:e.title}:{},type:e.type,url:e.url}})}:{isError:!0,result:{errorCode:l.content.error_code,type:l.content.type}},...eM(l.caller)}),Array.isArray(l.content))for(let e of l.content)f.push({type:"source",sourceType:"url",id:t(),url:e.url,...null!=e.title?{title:e.title}:{},providerMetadata:{anthropic:{pageAge:null!=(a=e.page_age)?a:null}}});break;case"code_execution_tool_result":f.push({type:"tool-result",toolCallId:l.tool_use_id,toolName:"code_execution",..."code_execution_tool_result_error"===l.content.type?{isError:!0,result:{errorCode:l.content.error_code,type:l.content.type}}:{result:l.content}});break;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":f.push({type:"tool-result",toolCallId:l.tool_use_id,toolName:"code_execution",result:l.content});break;case"tool_search_tool_result":{let e=null!=(i=v[l.tool_use_id])?i:"tool_search_tool_regex";f.push({type:"tool-result",toolCallId:l.tool_use_id,toolName:e,..."tool_search_tool_result_error"===l.content.type?{isError:!0,result:{errorCode:l.content.error_code,type:l.content.type}}:{result:l.content.tool_references.map(e=>({toolName:e.tool_name,type:e.type}))}});break}case"advisor_tool_result":"advisor_result"===l.content.type?f.push({type:"tool-result",toolCallId:l.tool_use_id,toolName:"advisor",result:{type:l.content.type,text:l.content.text,...null!=l.content.stop_reason?{stopReason:l.content.stop_reason}:{}}}):"advisor_redacted_result"===l.content.type?f.push({type:"tool-result",toolCallId:l.tool_use_id,toolName:"advisor",result:{type:l.content.type,encryptedContent:l.content.encrypted_content,...null!=l.content.stop_reason?{stopReason:l.content.stop_reason}:{}}}):f.push({type:"tool-result",toolCallId:l.tool_use_id,toolName:"advisor",isError:!0,result:{errorCode:l.content.error_code,type:l.content.type}})}return{content:f,finishReason:{unified:ei({finishReason:e.stop_reason}),raw:null!=(l=e.stop_reason)?l:void 0},usage:B({usage:e.usage}),response:{id:null!=(s=e.id)?s:void 0,modelId:null!=(u=e.model)?u:void 0},warnings:[],providerMetadata:{anthropic:(g=function(e){if(null!=e)return{type:e.type,...null!=e.category?{category:e.category}:{},...null!=e.explanation?{explanation:e.explanation}:{},...null!=e.recommended_model?{recommendedModel:e.recommended_model}:{}}}((c=e).stop_details),{usage:c.usage,stopSequence:null!=(d=c.stop_sequence)?d:null,...null!=g?{stopDetails:g}:{},iterations:c.usage.iterations?c.usage.iterations.map(e=>({type:e.type,...null!=e.model?{model:e.model}:{},inputTokens:e.input_tokens,outputTokens:e.output_tokens,...e.cache_creation_input_tokens?{cacheCreationInputTokens:e.cache_creation_input_tokens}:{},...e.cache_read_input_tokens?{cacheReadInputTokens:e.cache_read_input_tokens}:{}})):null,container:c.container?{expiresAt:c.container.expires_at,id:c.container.id,skills:null!=(m=null==(p=c.container.skills)?void 0:p.map(e=>({type:e.type,skillId:e.skill_id,version:e.version})))?m:null}:null,contextManagement:(h=c.context_management)?{appliedEdits:h.applied_edits.map(e=>{switch(e.type){case"clear_tool_uses_20250919":return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case"clear_thinking_20251015":return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens};case"compact_20260112":return{type:e.type}}})}:null})}}}(o,t)}}}}function eC(e){return{id:e,status:"failed",error:{message:"Anthropic returned an invalid Message batch result.",code:"invalid_response"}}}async function eE(e){let t=await (0,o.safeValidateTypes)({value:e,schema:m});if(t.success)return t.value;if(!(0,o.isRecord)(e)||!Array.isArray(e.content))return;let n=[];for(let t of e.content){let r=await (0,o.safeValidateTypes)({value:{...e,content:[t]},schema:m});if(r.success){let[e]=r.value.content;null!=e&&n.push(e)}else if(!(0,o.isRecord)(t)||"string"!=typeof t.type||ez.has(t.type))return}let r=await (0,o.safeValidateTypes)({value:{...e,content:n},schema:m});return r.success?r.value:void 0}function eM(e){return null==e?{}:{providerMetadata:{anthropic:{caller:{type:e.type,toolId:e.tool_id}}}}}var ej=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({command:n.z.string(),restart:n.z.boolean().optional()}))),eA=(0,o.createProviderDefinedToolFactory)({id:"anthropic.bash_20241022",inputSchema:ej}),eO=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({command:n.z.string(),restart:n.z.boolean().optional()}))),eR=(0,o.createProviderDefinedToolFactory)({id:"anthropic.bash_20250124",inputSchema:eO}),eN=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({action:n.z.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:n.z.array(n.z.number().int()).optional(),text:n.z.string().optional()}))),eP=(0,o.createProviderDefinedToolFactory)({id:"anthropic.computer_20241022",inputSchema:eN}),e$=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({action:n.z.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:n.z.tuple([n.z.number().int(),n.z.number().int()]).optional(),duration:n.z.number().optional(),scroll_amount:n.z.number().optional(),scroll_direction:n.z.enum(["up","down","left","right"]).optional(),start_coordinate:n.z.tuple([n.z.number().int(),n.z.number().int()]).optional(),text:n.z.string().optional()}))),eq=(0,o.createProviderDefinedToolFactory)({id:"anthropic.computer_20250124",inputSchema:e$}),eL=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({action:n.z.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:n.z.tuple([n.z.number().int(),n.z.number().int()]).optional(),duration:n.z.number().optional(),region:n.z.tuple([n.z.number().int(),n.z.number().int(),n.z.number().int(),n.z.number().int()]).optional(),scroll_amount:n.z.number().optional(),scroll_direction:n.z.enum(["up","down","left","right"]).optional(),start_coordinate:n.z.tuple([n.z.number().int(),n.z.number().int()]).optional(),text:n.z.string().optional()}))),eD=(0,o.createProviderDefinedToolFactory)({id:"anthropic.computer_20251124",inputSchema:eL}),eU=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.discriminatedUnion("command",[n.z.object({command:n.z.literal("view"),path:n.z.string(),view_range:n.z.tuple([n.z.number(),n.z.number()]).optional()}),n.z.object({command:n.z.literal("create"),path:n.z.string(),file_text:n.z.string()}),n.z.object({command:n.z.literal("str_replace"),path:n.z.string(),old_str:n.z.string(),new_str:n.z.string()}),n.z.object({command:n.z.literal("insert"),path:n.z.string(),insert_line:n.z.number(),insert_text:n.z.string()}),n.z.object({command:n.z.literal("delete"),path:n.z.string()}),n.z.object({command:n.z.literal("rename"),old_path:n.z.string(),new_path:n.z.string()})]))),eF=(0,o.createProviderDefinedToolFactory)({id:"anthropic.memory_20250818",inputSchema:eU}),eH=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({command:n.z.enum(["view","create","str_replace","insert","undo_edit"]),path:n.z.string(),file_text:n.z.string().optional(),insert_line:n.z.number().int().optional(),new_str:n.z.string().optional(),insert_text:n.z.string().optional(),old_str:n.z.string().optional(),view_range:n.z.array(n.z.number().int()).optional()}))),eB=(0,o.createProviderDefinedToolFactory)({id:"anthropic.text_editor_20241022",inputSchema:eH}),eV=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({command:n.z.enum(["view","create","str_replace","insert","undo_edit"]),path:n.z.string(),file_text:n.z.string().optional(),insert_line:n.z.number().int().optional(),new_str:n.z.string().optional(),insert_text:n.z.string().optional(),old_str:n.z.string().optional(),view_range:n.z.array(n.z.number().int()).optional()}))),eJ=(0,o.createProviderDefinedToolFactory)({id:"anthropic.text_editor_20250124",inputSchema:eV}),eW=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({command:n.z.enum(["view","create","str_replace","insert"]),path:n.z.string(),file_text:n.z.string().optional(),insert_line:n.z.number().int().optional(),new_str:n.z.string().optional(),insert_text:n.z.string().optional(),old_str:n.z.string().optional(),view_range:n.z.array(n.z.number().int()).optional()}))),eK=(0,o.createProviderDefinedToolFactory)({id:"anthropic.text_editor_20250429",inputSchema:eW}),eG=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.array(n.z.object({type:n.z.literal("tool_reference"),toolName:n.z.string()})))),eY=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({query:n.z.string(),limit:n.z.number().optional()}))),eX=(0,o.createProviderExecutedToolFactory)({id:"anthropic.tool_search_bm25_20251119",inputSchema:eY,outputSchema:eG,supportsDeferredResults:!0}),eZ={advisor_20260301:e=>x(e),bash_20241022:function(e={}){let{execute:t,...o}=e;return void 0===t?eA({...o,execute:async({command:e},{abortSignal:t,experimental_sandbox:o})=>{if(!o)throw Error("Sandbox session is not available");return await o.run({command:e,abortSignal:t})}}):eA({...o,...null===t?{}:{execute:t}})},bash_20250124:function(e={}){let{execute:t,...o}=e;return void 0===t?eR({...o,execute:async({command:e},{abortSignal:t,experimental_sandbox:o})=>{if(!o)throw Error("Sandbox session is not available");return await o.run({command:e,abortSignal:t})}}):eR({...o,...null===t?{}:{execute:t}})},codeExecution_20250522:(e={})=>W(e),codeExecution_20250825:(e={})=>(0,o.experimental_toolCaller)(Y(e),{type:"provider",prepareProviderOptions:e=>{var t;let o=null==e?void 0:e.anthropic;return{...e,anthropic:{...o,allowedCallers:[...new Set([...null!=(t=null==o?void 0:o.allowedCallers)?t:[],"code_execution_20250825"])]}}}}),codeExecution_20260120:(e={})=>(0,o.experimental_toolCaller)(Q(e),{type:"provider",prepareProviderOptions:e=>{var t;let o=null==e?void 0:e.anthropic;return{...e,anthropic:{...o,allowedCallers:[...new Set([...null!=(t=null==o?void 0:o.allowedCallers)?t:[],"code_execution_20260120"])]}}}}),computer_20241022:eP,computer_20250124:eq,computer_20251124:eD,memory_20250818:eF,textEditor_20241022:eB,textEditor_20250124:eJ,textEditor_20250429:eK,textEditor_20250728:(e={})=>I(e),webFetch_20250910:(e={})=>F(e),webFetch_20260209:(e={})=>q(e),webSearch_20250305:(e={})=>R(e),webSearch_20260209:(e={})=>M(e),toolSearchRegex_20251119:(e={})=>eo(e),toolSearchBm25_20251119:(e={})=>eX(e)},eQ=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({id:n.z.string(),display_title:n.z.string().nullish(),name:n.z.string().nullish(),description:n.z.string().nullish(),latest_version:n.z.string().nullish(),source:n.z.string(),created_at:n.z.string(),updated_at:n.z.string()})));(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({data:n.z.array(n.z.object({version:n.z.string()}))})));var e0=(0,o.lazySchema)(()=>(0,o.zodSchema)(n.z.object({type:n.z.string(),skill_id:n.z.string(),name:n.z.string().nullish(),description:n.z.string().nullish()})));function e1(e){let t=encodeURIComponent(e);return"."===t?"%252E":".."===t?"%252E%252E":t}var e2=class{constructor(e){this.config=e,this.specificationVersion="v4"}get provider(){return this.config.provider}async getHeaders(){return(0,o.combineHeaders)(await (0,o.resolve)(this.config.headers),{"anthropic-beta":"skills-2025-10-02"})}async fetchVersionMetadata({skillId:e,version:t,headers:n}){let{value:r}=await (0,o.getFromApi)({url:`${this.config.baseURL}/skills/${e1(e)}/versions/${e1(t)}`,validateUrl:!1,headers:n,failedResponseHandler:i,successfulResponseHandler:(0,o.createJsonResponseHandler)(e0),fetch:this.config.fetch});return{...null!=r.name?{name:r.name}:{},...null!=r.description?{description:r.description}:{}}}async uploadSkill(e){var t,n;let r=new FormData;for(let t of(null!=e.displayTitle&&r.append("display_title",e.displayTitle),e.files)){let e=(0,o.convertInlineFileDataToUint8Array)(t.data);r.append("files[]",new Blob([e]),t.path)}let a=await this.getHeaders(),{value:l}=await (0,o.postFormDataToApi)({url:`${this.config.baseURL}/skills`,headers:a,formData:r,failedResponseHandler:i,successfulResponseHandler:(0,o.createJsonResponseHandler)(eQ),fetch:this.config.fetch}),s=null!=l.latest_version?await this.fetchVersionMetadata({skillId:l.id,version:l.latest_version,headers:a}):{},u=null!=(t=s.name)?t:l.name,c=null!=(n=s.description)?n:l.description;return{providerReference:{anthropic:l.id},...null!=l.display_title?{displayTitle:l.display_title}:{},...null!=u?{name:u}:{},...null!=c?{description:c}:{},...null!=l.latest_version?{latestVersion:l.latest_version}:{},providerMetadata:{anthropic:{...null!=l.source?{source:l.source}:{},...null!=l.created_at?{createdAt:l.created_at}:{},...null!=l.updated_at?{updatedAt:l.updated_at}:{}}},warnings:[]}}},e4="https://api.anthropic.com",e3=`${e4}/v1`;function e6(e={}){var n,r,a;let i,l=null!=(a=(0,o.loadOptionalSetting)({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"}),n=(i=(0,o.withoutTrailingSlash)((0,o.validateBaseURL)(a)))===e4?e3:i)?n:e3,u=null!=(r=e.name)?r:"anthropic.messages";if(e.apiKey&&e.authToken)throw new t.InvalidArgumentError({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let c=()=>{let t=e.authToken?{Authorization:`Bearer ${e.authToken}`}:{"x-api-key":(0,o.loadApiKey)({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return(0,o.withUserAgentSuffix)({"anthropic-version":"2023-06-01",...t,...e.headers},"ai-sdk/anthropic/4.0.49")},d=t=>{var n;return new eS(t,{provider:u,baseURL:l,headers:c,fetch:e.fetch,generateId:null!=(n=e.generateId)?n:o.generateId,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},p=function(e){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return d(e)};return p.specificationVersion="v4",p.languageModel=d,p.chat=d,p.messages=d,p.embeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:"embeddingModel"})},p.textEmbeddingModel=p.embeddingModel,p.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:"imageModel"})},p.files=()=>new s({provider:u,baseURL:l,headers:c,fetch:e.fetch}),p.skills=()=>new e2({provider:`${u.replace(".messages","")}.skills`,baseURL:l,headers:c,fetch:e.fetch}),p.tools=eZ,p}e6(),e.s(["createAnthropic",0,e6])},19698,e=>{"use strict";var t=e.i(691296),o=e.i(296194),n=e.i(548874),r=e.i(853205),a=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string(),details:r.z.array(r.z.unknown()).nullish()})}))),i=(0,t.createJsonErrorResponseHandler)({errorSchema:a,errorToMessage:e=>e.error.message}),l=r.z.union([r.z.object({text:r.z.string()}),r.z.object({inlineData:r.z.object({mimeType:r.z.string(),data:r.z.string()})}),r.z.object({fileData:r.z.object({fileUri:r.z.string(),mimeType:r.z.string()})})]),s=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),content:r.z.array(r.z.array(l).min(1).nullable()).optional()}))),u=class e{constructor(e,t){this.specificationVersion="v4",this.maxEmbeddingsPerCall=100,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}static[n.WORKFLOW_SERIALIZE](e){return(0,t.serializeModelOptions)({modelId:e.modelId,config:e.config})}static[n.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:a}){let l=await (0,t.parseProviderOptions)({provider:"google",providerOptions:a,schema:s});if(e.length>this.maxEmbeddingsPerCall)throw new o.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let u=(0,t.combineHeaders)(this.config.headers?await (0,t.resolve)(this.config.headers):void 0,n),p=null==l?void 0:l.content;if(null!=p&&p.length!==e.length)throw Error(`The number of multimodal content entries (${p.length}) must match the number of values (${e.length}).`);if(1===e.length){let o=null==p?void 0:p[0],n=e[0]?[{text:e[0]}]:[],a=null!=o?[...n,...o]:[{text:e[0]}],{responseHeaders:s,value:c,rawValue:m}=await (0,t.postJsonToApi)({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:u,body:{model:`models/${this.modelId}`,content:{parts:a},outputDimensionality:null==l?void 0:l.outputDimensionality,taskType:null==l?void 0:l.taskType},failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(d),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:[c.embedding.values],usage:void 0,response:{headers:s,body:m}}}let{responseHeaders:m,value:h,rawValue:g}=await (0,t.postJsonToApi)({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:u,body:{requests:e.map((e,t)=>{let o=null==p?void 0:p[t];return{model:`models/${this.modelId}`,content:{role:"user",parts:null!=o?[...e?[{text:e}]:[],...o]:[{text:e}]},outputDimensionality:null==l?void 0:l.outputDimensionality,taskType:null==l?void 0:l.taskType}})},failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(c),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:h.embeddings.map(e=>e.values),usage:void 0,response:{headers:m,body:g}}}},c=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}))),d=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})})));function p(e){return e.includes("/")?e:`models/${e}`}function m(e){var o,n,r,a;if(null==e)return(0,t.createNullLanguageModelUsage)();let i=null!=(o=e.promptTokenCount)?o:0,l=null!=(n=e.candidatesTokenCount)?n:0,s=null!=(r=e.cachedContentTokenCount)?r:0,u=null!=(a=e.thoughtsTokenCount)?a:0;return{inputTokens:{total:i,noCache:i-s,cacheRead:s,cacheWrite:void 0},outputTokens:{total:l+u,text:l,reasoning:u},raw:e}}var h="recursive JSON Schema reference:";function g(e,t=!0){let n="object"==typeof e?e:void 0;return function e(t,n,r){var a;if(null==t)return;if("boolean"==typeof t)return{type:"boolean",properties:{}};if(null!=t.$ref)return function({jsonSchema:t,reference:n,isRoot:r,referenceContext:a}){let{definition:i,referenceKey:l}=function(e,t){let o,n=[{prefix:"#/$defs/",definitions:t.dollarDefinitions},{prefix:"#/definitions/",definitions:t.definitions}].find(({prefix:t})=>e.startsWith(t)),r=n?e.slice(n.prefix.length):void 0;(null==n||null==r||0===r.length||r.includes("/"))&&f(e);try{o=decodeURIComponent(r)}catch(t){f(e)}(o.includes("/")||/~(?![01])/u.test(o)||null==n.definitions)&&f(e);let a=o.replace(/~[01]/g,e=>"~1"===e?"/":"~");return Object.prototype.hasOwnProperty.call(n.definitions,a)||f(e),{definition:n.definitions[a],referenceKey:`${n.prefix}${a}`}}(n,a);if(a.resolvingReferences.has(l))throw new o.UnsupportedFunctionalityError({functionality:`${h} ${n}`,message:"Google schema conversion does not support recursive JSON Schema references."});let s=new Set(a.resolvingReferences);s.add(l);let{$ref:u,...c}=t;return e("boolean"==typeof i?!!i&&c:{...i,...c},r,{...a,resolvingReferences:s})}({jsonSchema:t,reference:t.$ref,isRoot:n,referenceContext:r});if(null!=(a=t)&&"object"==typeof a&&"object"===a.type&&(null==a.properties||0===Object.keys(a.properties).length)&&!a.additionalProperties)return n?void 0:t.description?{type:"object",description:t.description}:{type:"object"};let{type:i,description:l,required:s,properties:u,items:c,allOf:d,anyOf:p,oneOf:m,format:g,const:y,minLength:v,minItems:_,maxItems:b,enum:z}=t,w={};if(l&&(w.description=l),s&&(w.required=s),g&&(w.format=g),i)if(Array.isArray(i)){let e=i.includes("null"),t=i.filter(e=>"null"!==e);0===t.length?w.type="null":(w.anyOf=t.map(e=>({type:e})),e&&(w.nullable=!0))}else w.type=i;let x=null!=z?z:void 0!==y?[y]:void 0;if(void 0!==x&&function({values:e,type:t,result:n}){let r=Array.isArray(t)&&t.includes("null")||void 0===t&&e.includes(null),a=r?e.filter(e=>null!==e):e;if(e.length>0&&e.every(e=>null===e)&&(void 0===t||"null"===t||Array.isArray(t)&&t.includes("null"))){n.type="null",Array.isArray(t)&&delete n.anyOf;return}let i=function({values:e,type:t}){if(0===e.length)return;let o=e=>void 0===t||t===e||Array.isArray(t)&&t.includes(e);if(o("string")&&e.every(e=>"string"==typeof e))return"string";if((o("number")||o("integer"))&&e.every(e=>"number"==typeof e&&Number.isFinite(e))){if(o("number"))return"number";if(e.every(e=>Number.isInteger(e)))return"integer"}if(o("boolean")&&e.every(e=>"boolean"==typeof e))return"boolean"}({values:a,type:t});if(void 0===i)throw new o.UnsupportedFunctionalityError({functionality:"JSON Schema enum with mixed or unsupported values",message:"Google does not support this JSON Schema enum. Enum values must share one supported primitive type and match the schema type."});n.type=i,Array.isArray(t)&&delete n.anyOf,r&&(n.nullable=!0),"string"===i?n.enum=a:(n.format="enum",n.enum=a.map(String))}({values:x,type:i,result:w}),null!=u&&(w.properties=Object.entries(u).reduce((t,[o,n])=>(t[o]=e(n,!1,r),t),{})),c&&(w.items=Array.isArray(c)?c.map(t=>e(t,!1,r)):e(c,!1,r)),d&&(w.allOf=d.map(t=>e(t,!1,r))),p)if(p.some(e=>"object"==typeof e&&(null==e?void 0:e.type)==="null")){let t=p.filter(e=>"object"!=typeof e||(null==e?void 0:e.type)!=="null");if(1===t.length){let o=e(t[0],!1,r);"object"==typeof o&&(w.nullable=!0,Object.assign(w,o))}else w.anyOf=t.map(t=>e(t,!1,r)),w.nullable=!0}else w.anyOf=p.map(t=>e(t,!1,r));return m&&(w.oneOf=m.map(t=>e(t,!1,r))),void 0!==v&&(w.minLength=v),void 0!==_&&(w.minItems=_),void 0!==b&&(w.maxItems=b),w}(e,t,{definitions:null==n?void 0:n.definitions,dollarDefinitions:null==n?void 0:n.$defs,resolvingReferences:new Set})}function f(e){throw new o.UnsupportedFunctionalityError({functionality:`JSON Schema reference: ${e}`,message:"Google schema conversion only supports references to direct children of root-level $defs or definitions."})}var y=/^data:([^;,]+);base64,(.+)$/s,v=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({responseModalities:r.z.array(r.z.enum(["TEXT","IMAGE"])).optional(),thinkingConfig:r.z.object({thinkingBudget:r.z.number().optional(),includeThoughts:r.z.boolean().optional(),thinkingLevel:r.z.enum(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:r.z.string().optional(),structuredOutputs:r.z.boolean().optional(),safetySettings:r.z.array(r.z.object({category:r.z.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:r.z.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:r.z.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:r.z.boolean().optional(),labels:r.z.record(r.z.string(),r.z.string()).optional(),mediaResolution:r.z.enum(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:r.z.object({aspectRatio:r.z.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).optional(),imageSize:r.z.enum(["1K","2K","4K","512"]).optional(),personGeneration:r.z.enum(["PERSON_GENERATION_UNSPECIFIED","ALLOW_ALL","ALLOW_ADULT","ALLOW_NONE"]).optional(),prominentPeople:r.z.enum(["PROMINENT_PEOPLE_UNSPECIFIED","ALLOW_PROMINENT_PEOPLE","BLOCK_PROMINENT_PEOPLE"]).optional(),imageOutputOptions:r.z.object({mimeType:r.z.enum(["image/jpeg","image/png"]).optional(),compressionQuality:r.z.number().optional()}).optional()}).optional(),retrievalConfig:r.z.object({latLng:r.z.object({latitude:r.z.number(),longitude:r.z.number()}).optional()}).optional(),streamFunctionCallArguments:r.z.boolean().optional(),serviceTier:r.z.enum(["standard","flex","priority"]).optional(),sharedRequestType:r.z.enum(["priority","flex","standard"]).optional(),requestType:r.z.enum(["shared"]).optional()}))),_=/(^|\/)gemini-1(?:[.-]|$)/i,b=/(^|\/)gemini-2(?:[.-]|$)/i,z=/(^|\/)gemini-2\.5(?:[.-]|$)/i,w=/(^|\/)gemini-/i;function x(e){let t=w.test(e),o=b.test(e),n=_.test(e)||/(^|\/)gemini-pro(?:-vision)?$/i.test(e)||/(^|\/)gemini-robotics-er-1\.5(?:[.-]|$)/i.test(e),r=t&&!(n||o);return{supportsGemini2Tools:t&&!n||e.toLowerCase().includes("nano-banana"),supportsFileSearch:z.test(e)||r,usesGemini3Features:r}}function S(e){var t;let n={name:e.name,description:null!=(t=e.description)?t:""};try{return{...n,parameters:g(e.inputSchema)}}catch(t){if(!(o.UnsupportedFunctionalityError.isInstance(t)&&t.functionality.startsWith(h)))throw t;return{...n,parametersJsonSchema:e.inputSchema}}}var k=class{constructor(){this.accumulatedArgs={},this.jsonText="",this.pathStack=[],this.stringOpen=!1}processPartialArgs(e){let t="";for(let o of e){let e=o.jsonPath.replace(/^\$\./,"");if(!e)continue;let n=function(e){let t=[];for(let o of e.split(".")){let e=o.indexOf("[");if(-1===e)t.push(o);else for(let n of(e>0&&t.push(o.slice(0,e)),o.matchAll(/\[(\d+)\]/g)))t.push(parseInt(n[1],10))}return t}(e),r=function(e,t){let o=e;for(let e of t){if(null==o||"object"!=typeof o)return;let t=o;if(!I.call(t,e))return;o=t[e]}return o}(this.accumulatedArgs,n);if(null!=o.stringValue&&void 0!==r){let e=JSON.stringify(o.stringValue).slice(1,-1);C(this.accumulatedArgs,n,r+o.stringValue),t+=e;continue}let a=function(e){var t,o;let n=null!=(o=null!=(t=e.stringValue)?t:e.numberValue)?o:e.boolValue;return null!=n?{value:n,json:JSON.stringify(n)}:"nullValue"in e?{value:null,json:"null"}:void 0}(o);null!=a&&(C(this.accumulatedArgs,n,a.value),t+=this.emitNavigationTo(n,o,a.json))}return this.jsonText+=t,{currentJSON:this.accumulatedArgs,textDelta:t}}finalize(){let e=JSON.stringify(this.accumulatedArgs),t=e.slice(this.jsonText.length);return{finalJSON:e,closingDelta:t}}ensureRoot(){return 0===this.pathStack.length?(this.pathStack.push({segment:"",isArray:!1,childCount:0}),"{"):""}emitNavigationTo(e,t,o){let n="";this.stringOpen&&(n+='"',this.stringOpen=!1),n+=this.ensureRoot();let r=e.slice(0,-1),a=e[e.length-1],i=this.findCommonStackDepth(r);return n+=this.closeDownTo(i),n+=this.openDownTo(r,a),n+=this.emitLeaf(a,t,o)}findCommonStackDepth(e){let t=Math.min(this.pathStack.length-1,e.length),o=0;for(let n=0;n<t;n++)if(this.pathStack[n+1].segment===e[n])o++;else break;return o+1}closeDownTo(e){let t="";for(;this.pathStack.length>e;)t+=this.pathStack.pop().isArray?"]":"}";return t}openDownTo(e,t){let o="",n=this.pathStack.length-1;for(let r=n;r<e.length;r++){let n=e[r],a=this.pathStack[this.pathStack.length-1];a.childCount>0&&(o+=","),a.childCount++,"string"==typeof n&&(o+=`${JSON.stringify(n)}:`);let i="number"==typeof(r+1<e.length?e[r+1]:t);o+=i?"[":"{",this.pathStack.push({segment:n,isArray:i,childCount:0})}return o}emitLeaf(e,t,o){let n="",r=this.pathStack[this.pathStack.length-1];return r.childCount>0&&(n+=","),r.childCount++,"string"==typeof e&&(n+=`${JSON.stringify(e)}:`),null!=t.stringValue&&t.willContinue?(n+=o.slice(0,-1),this.stringOpen=!0):n+=o,n}},I=Object.prototype.hasOwnProperty;function T(e,t,o){Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0})}function C(e,t,o){let n=e;for(let e=0;e<t.length-1;e++){var r;let o=t[e],a=t[e+1];r=n,I.call(r,o)&&null!=n[o]||T(n,o,"number"==typeof a?[]:{}),n=n[o]}T(n,t[t.length-1],o)}function E({finishReason:e,hasToolCalls:t}){switch(e){case"STOP":return t?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";default:return"other"}}var M=["HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT"],j=/(^|\/)gemini-2\.5(?:[.-]|$)/i,A=class e{constructor(e,o){var n;this.specificationVersion="v4",this.modelId=e,this.config=o,this.generateId=null!=(n=o.generateId)?n:t.generateId}static[n.WORKFLOW_SERIALIZE](e){return(0,t.serializeModelOptions)({modelId:e.modelId,config:e.config})}static[n.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}get supportedUrls(){var e,t,o;return null!=(o=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?o:{}}async getArgs({prompt:e,maxOutputTokens:n,temperature:r,topP:a,topK:i,frequencyPenalty:l,presencePenalty:s,stopSequences:u,responseFormat:c,seed:d,tools:p,toolChoice:m,reasoning:h,providerOptions:f},{isStreaming:_=!1}={}){var b,z,w;let k,I=[],T=this.config.provider.includes("vertex")?["googleVertex","vertex"]:["google"];for(let e of T)if(null!=(k=await (0,t.parseProviderOptions)({provider:e,providerOptions:f,schema:v})))break;null!=k||T.includes("google")||(k=await (0,t.parseProviderOptions)({provider:"google",providerOptions:f,schema:v}));let C=this.config.provider.startsWith("google.vertex.");(null==p?void 0:p.some(e=>"provider"===e.type&&"google.vertex_rag_store"===e.id))&&!C&&I.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`}),(null==k?void 0:k.streamFunctionCallArguments)&&!C&&I.push({type:"other",message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`}),(null==k?void 0:k.serviceTier)&&C&&I.push({type:"other",message:"'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo"}),((null==k?void 0:k.sharedRequestType)||(null==k?void 0:k.requestType))&&!C&&I.push({type:"other",message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${this.config.provider}).`});let E=C&&((null==k?void 0:k.sharedRequestType)||(null==k?void 0:k.requestType))?{...k.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":k.sharedRequestType},...k.requestType&&{"X-Vertex-AI-LLM-Request-Type":k.requestType}}:void 0,A=C||null==k?void 0:k.serviceTier,O=null==k?void 0:k.imageConfig;if(null!=O&&!C){let{personGeneration:e,prominentPeople:t,imageOutputOptions:o,...n}=O,r=Object.entries({personGeneration:e,prominentPeople:t,imageOutputOptions:o}).filter(([,e])=>null!=e).map(([e])=>`'imageConfig.${e}'`);r.length>0&&(I.push({type:"other",message:`${r.join(", ")} ${1===r.length?"is a Vertex AI option and is":"are Vertex AI options and are"} ignored with the current Google provider (${this.config.provider}).`}),O=n)}let R=this.modelId.toLowerCase().startsWith("gemma-"),N=!C&&j.test(this.modelId);N&&null!=l&&I.push({type:"unsupported",feature:"frequencyPenalty"}),N&&null!=s&&I.push({type:"unsupported",feature:"presencePenalty"});let{usesGemini3Features:P}=x(this.modelId),{contents:$,systemInstruction:q}=function(e,n){var r,a,i,l,s,u;let c=[],d=[],p=!0,m=null!=(r=null==n?void 0:n.isGemmaModel)&&r,h=null!=(a=null==n?void 0:n.isGemini3Model)&&a,g=null==n?void 0:n.onWarning,f=null!=(i=null==n?void 0:n.providerOptionsNames)?i:["google"],v=!f.includes("google"),_=null==(l=null==n?void 0:n.supportsFunctionResponseParts)||l,b=null==(s=null==n?void 0:n.includeFunctionCallIds)||s,z=!1,w=[],x=e=>(w.push(e),z=!0,"skip_thought_signature_validator"),S=e=>{var t,o,n,r,a;for(let o of f){let n=null==(t=e.providerOptions)?void 0:t[o];if(null!=n)return n}return v?null==(o=e.providerOptions)?void 0:o.google:null!=(a=null==(n=e.providerOptions)?void 0:n.googleVertex)?a:null==(r=e.providerOptions)?void 0:r.vertex};for(let{role:n,content:r}of e)switch(n){case"system":if(!p)throw new o.UnsupportedFunctionalityError({functionality:"system messages are only supported at the beginning of the conversation"});c.push({text:r});break;case"user":{p=!1;let e=[];for(let n of r)switch(n.type){case"text":e.push({text:n.text});break;case"file":switch(n.data.type){case"url":e.push({fileData:{mimeType:(0,t.resolveFullMediaType)({part:n}),fileUri:n.data.url.toString()}});break;case"reference":if(v)throw new o.UnsupportedFunctionalityError({functionality:"file parts with provider references"});e.push({fileData:{mimeType:(0,t.resolveFullMediaType)({part:n}),fileUri:(0,t.resolveProviderReference)({reference:n.data.reference,provider:"google"})}});break;case"text":e.push({inlineData:{mimeType:(0,t.isFullMediaType)(n.mediaType)?n.mediaType:"text/plain",data:(0,t.convertToBase64)(new TextEncoder().encode(n.data.text))}});break;case"data":e.push({inlineData:{mimeType:(0,t.resolveFullMediaType)({part:n}),data:(0,t.convertToBase64)(n.data.data)}})}}d.push({role:"user",parts:e});break}case"assistant":{p=!1;let e=!1;d.push({role:"model",parts:r.map(n=>{let r=S(n),a=(null==r?void 0:r.thoughtSignature)!=null?String(r.thoughtSignature):void 0;switch(n.type){case"text":return 0===n.text.length?void 0:{text:n.text,thoughtSignature:a};case"reasoning":return 0===n.text.length?void 0:{text:n.text,thought:!0,thoughtSignature:a};case"reasoning-file":switch(n.data.type){case"url":throw new o.UnsupportedFunctionalityError({functionality:"File data URLs in assistant messages are not supported"});case"data":return{inlineData:{mimeType:n.mediaType,data:(0,t.convertToBase64)(n.data.data)},thought:!0,thoughtSignature:a}}break;case"file":switch(n.data.type){case"url":throw new o.UnsupportedFunctionalityError({functionality:"File data URLs in assistant messages are not supported"});case"reference":if(v)throw new o.UnsupportedFunctionalityError({functionality:"file parts with provider references"});return{fileData:{mimeType:n.mediaType,fileUri:(0,t.resolveProviderReference)({reference:n.data.reference,provider:"google"})},...(null==r?void 0:r.thought)===!0?{thought:!0}:{},thoughtSignature:a};case"text":return{inlineData:{mimeType:(0,t.isFullMediaType)(n.mediaType)?n.mediaType:"text/plain",data:(0,t.convertToBase64)(new TextEncoder().encode(n.data.text))},...(null==r?void 0:r.thought)===!0?{thought:!0}:{},thoughtSignature:a};case"data":return{inlineData:{mimeType:n.mediaType,data:(0,t.convertToBase64)(n.data.data)},...(null==r?void 0:r.thought)===!0?{thought:!0}:{},thoughtSignature:a}}break;case"tool-call":{let o=(null==r?void 0:r.serverToolCallId)!=null?String(r.serverToolCallId):void 0,i=(null==r?void 0:r.serverToolType)!=null?String(r.serverToolType):void 0,l=null!=o&&null!=i,s=!l&&null==a&&e,u=null!=a?a:h&&!s?x(n.toolName):void 0;if(l||null==a||(e=!0),l)return{toolCall:{toolType:i,args:"string"==typeof n.input?(0,t.secureJsonParse)(n.input):n.input,id:o},thoughtSignature:u};return{functionCall:{...b&&null!=n.toolCallId?{id:n.toolCallId}:{},name:n.toolName,args:n.input},thoughtSignature:u}}case"tool-result":{let e=(null==r?void 0:r.serverToolCallId)!=null?String(r.serverToolCallId):void 0,t=(null==r?void 0:r.serverToolType)!=null?String(r.serverToolType):void 0;if(e&&t)return{toolResponse:{toolType:t,response:"json"===n.output.type?n.output.value:{},id:e},thoughtSignature:a};return}}}).filter(e=>void 0!==e)});break}case"tool":{p=!1;let e=[];for(let o of r){if("tool-approval-response"===o.type)continue;let n=S(o),r=(null==n?void 0:n.serverToolCallId)!=null?String(n.serverToolCallId):void 0,a=(null==n?void 0:n.serverToolType)!=null?String(n.serverToolType):void 0;if(r&&a){let e=(null==n?void 0:n.thoughtSignature)!=null?String(n.thoughtSignature):void 0;if(d.length>0){let t=d[d.length-1];if("model"===t.role){t.parts.push({toolResponse:{toolType:a,response:"json"===o.output.type?o.output.value:{},id:r},thoughtSignature:e});continue}}}let i=o.output;"content"===i.type?_?function(e,o,n,r,a=!0){let i=[],l=[];for(let e of n)switch(e.type){case"text":l.push(e.text);break;case"file":if("data"===e.data.type)i.push({inlineData:{mimeType:(0,t.resolveFullMediaType)({part:e}),data:(0,t.convertToBase64)(e.data.data)}});else if("url"===e.data.type){let t=function(e){let t=function(e){let t=y.exec(e);if(null!=t)return{mediaType:t[1],data:t[2]}}(e);if(null!=t)return{inlineData:{mimeType:t.mediaType,data:t.data}}}(e.data.url.toString());null!=t?i.push(t):l.push(JSON.stringify(e))}else l.push(JSON.stringify(e));break;default:l.push(JSON.stringify(e))}e.push({functionResponse:{...a&&null!=r?{id:r}:{},name:o,response:{name:o,content:l.length>0?l.join("\n"):"Tool executed successfully."},...i.length>0?{parts:i}:{}}})}(e,o.toolName,i.value,o.toolCallId,b):function(e,o,n,r,a=!0){for(let i of n)switch(i.type){case"text":e.push({functionResponse:{...a&&null!=r?{id:r}:{},name:o,response:{name:o,content:i.text}}});break;case"file":if("data"===i.data.type){let o=(0,t.getTopLevelMediaType)(i.mediaType);e.push({inlineData:{mimeType:(0,t.resolveFullMediaType)({part:i}),data:(0,t.convertToBase64)(i.data.data)}},{text:`Tool executed successfully and returned this ${"image"===o?"image":"file"} as a response`})}else e.push({text:JSON.stringify(i)});break;default:e.push({text:JSON.stringify(i)})}}(e,o.toolName,i.value,o.toolCallId,b):e.push({functionResponse:{...b&&null!=o.toolCallId?{id:o.toolCallId}:{},name:o.toolName,response:{name:o.toolName,content:"execution-denied"===i.type?null!=(u=i.reason)?u:"Tool call execution denied.":i.value}}})}d.push({role:"user",parts:e})}}if(m&&c.length>0&&d.length>0&&"user"===d[0].role){let e=c.map(e=>e.text).join("\n\n");d[0].parts.unshift({text:e+"\n\n"})}if(z&&null!=g){let e=Array.from(new Set(w));g({type:"other",message:`Replayed ${w.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${e.map(e=>`\`${e}\``).join(", ")}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`})}return{systemInstruction:c.length>0&&!m?{parts:c}:void 0,contents:d}}(e,{isGemmaModel:R,isGemini3Model:P,onWarning:e=>I.push(e),providerOptionsNames:T,supportsFunctionResponseParts:P,includeFunctionCallIds:!C}),{tools:L,toolConfig:D,toolWarnings:U}=function({tools:e,toolChoice:t,modelId:n,isVertexProvider:r=!1}){e=(null==e?void 0:e.length)?e:void 0;let a=[],{supportsGemini2Tools:i,supportsFileSearch:l,usesGemini3Features:s}=x(n);if(null==e)return{tools:void 0,toolConfig:void 0,toolWarnings:a};let u=e.some(e=>"function"===e.type),c=e.some(e=>"provider"===e.type);if(u&&c&&!s&&a.push({type:"unsupported",feature:"combination of function and provider-defined tools"}),c){let o=[];if(e.filter(e=>"provider"===e.type).forEach(e=>{switch(e.id){case"google.google_search":i?o.push({googleSearch:{...e.args}}):a.push({type:"unsupported",feature:`provider-defined tool ${e.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":i?o.push({enterpriseWebSearch:{}}):a.push({type:"unsupported",feature:`provider-defined tool ${e.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":i?o.push({urlContext:{}}):a.push({type:"unsupported",feature:`provider-defined tool ${e.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":i?o.push({codeExecution:{}}):a.push({type:"unsupported",feature:`provider-defined tool ${e.id}`,details:"The code execution tool is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":l?o.push({fileSearch:{...e.args}}):a.push({type:"unsupported",feature:`provider-defined tool ${e.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":i?o.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:e.args.ragCorpus},similarity_top_k:e.args.topK}}}):a.push({type:"unsupported",feature:`provider-defined tool ${e.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":i?o.push({googleMaps:{}}):a.push({type:"unsupported",feature:`provider-defined tool ${e.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:a.push({type:"unsupported",feature:`provider-defined tool ${e.id}`})}}),u&&s&&o.length>0){let n=[];for(let t of e)"function"===t.type&&n.push(S(t));let i={functionCallingConfig:{mode:"VALIDATED"},...!r&&{includeServerSideToolInvocations:!0}};if(null!=t)switch(t.type){case"auto":break;case"none":i.functionCallingConfig={mode:"NONE"};break;case"required":i.functionCallingConfig={mode:"ANY"};break;case"tool":i.functionCallingConfig={mode:"ANY",allowedFunctionNames:[t.toolName]}}return{tools:[...o,{functionDeclarations:n}],toolConfig:i,toolWarnings:a}}return{tools:o.length>0?o:void 0,toolConfig:void 0,toolWarnings:a}}let d=[],p=!1;for(let t of e)"function"===t.type?(d.push(S(t)),!0===t.strict&&(p=!0)):a.push({type:"unsupported",feature:`function tool ${t.name}`});if(null==t)return{tools:[{functionDeclarations:d}],toolConfig:p?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:a};let m=t.type;switch(m){case"auto":return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:p?"VALIDATED":"AUTO"}},toolWarnings:a};case"none":return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:a};case"required":return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:a};case"tool":return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t.toolName]}},toolWarnings:a};default:throw new o.UnsupportedFunctionalityError({functionality:`tool choice type: ${m}`})}}({tools:p,toolChoice:m,modelId:this.modelId,isVertexProvider:C}),F=(0,t.createToolNameMapping)({tools:p,providerToolNames:{"google.code_execution":"code_execution"}}),H=function({reasoning:e,modelId:o,warnings:n}){if((0,t.isCustomReasoning)(e))return x(o).usesGemini3Features&&!o.includes("gemini-3-pro-image")?function({reasoning:e,modelId:o,warnings:n}){let r=function(e){var t;let o=null==(t=e.split("/").at(-1))?void 0:t.toLowerCase();if("gemini-flash-latest"===o)return"low";let n=/^gemini-(\d+)\.(\d+)-flash(?:$|-(?!lite(?:-|$)))/.exec(null!=o?o:"");if(null==n)return"minimal";let r=Number(n[1]),a=Number(n[2]);return r>3||3===r&&a>=7?"low":"minimal"}(o);if("none"===e)return{thinkingLevel:r};let a=(0,t.mapReasoningToProviderEffort)({reasoning:e,effortMap:{minimal:r,low:"low",medium:"medium",high:"high",xhigh:"high"},warnings:n});if(null!=a)return{thinkingLevel:a}}({reasoning:e,modelId:o,warnings:n}):function({reasoning:e,modelId:o,warnings:n}){let r;if("none"===e)return{thinkingBudget:0};let a=(0,t.mapReasoningToProviderBudget)({reasoning:e,maxOutputTokens:65536,maxReasoningBudget:(r=o.toLowerCase()).includes("2.5-pro")||r.includes("gemini-3-pro-image")?32768:24576,minReasoningBudget:0,warnings:n});if(null!=a)return{thinkingBudget:a}}({reasoning:e,modelId:o,warnings:n})}({reasoning:h,modelId:this.modelId,warnings:I}),B=(null==k?void 0:k.thinkingConfig)||H?{...H,...null==k?void 0:k.thinkingConfig}:void 0,V=_&&C?null!=(b=null==k?void 0:k.streamFunctionCallArguments)&&b:void 0,J=null==k?void 0:k.threshold,W=null!=(z=null==k?void 0:k.safetySettings)?z:null!=J?M.map(e=>({category:e,threshold:J})):void 0,K=D||V||(null==k?void 0:k.retrievalConfig)?{...D,...V&&{functionCallingConfig:{...null==D?void 0:D.functionCallingConfig,streamFunctionCallArguments:!0}},...(null==k?void 0:k.retrievalConfig)&&{retrievalConfig:k.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:n,temperature:r,topK:i,topP:a,frequencyPenalty:N?void 0:l,presencePenalty:N?void 0:s,stopSequences:u,seed:d,responseMimeType:(null==c?void 0:c.type)==="json"?"application/json":void 0,responseSchema:(null==c?void 0:c.type)==="json"&&null!=c.schema&&(null==(w=null==k?void 0:k.structuredOutputs)||w)?g(c.schema):void 0,...(null==k?void 0:k.audioTimestamp)&&{audioTimestamp:k.audioTimestamp},responseModalities:null==k?void 0:k.responseModalities,thinkingConfig:B,...(null==k?void 0:k.mediaResolution)&&{mediaResolution:k.mediaResolution},...O&&{imageConfig:O}},contents:$,systemInstruction:R?void 0:q,safetySettings:W,tools:L,toolConfig:K,cachedContent:null==k?void 0:k.cachedContent,labels:null==k?void 0:k.labels,serviceTier:A},warnings:[...I,...U],providerOptionsNames:T,extraHeaders:E,toolNameMapping:F}}convertGenerateContentResponse({response:e,warnings:t,providerOptionsNames:o,toolNameMapping:n}){var r,a,i,l,s,u,c,d,p,h,g,f,y,v,_,b,z,w,x,S,k;let I,T,C=e=>Object.fromEntries(o.map(t=>[t,e])),M=null==(r=e.candidates)?void 0:r[0],j=null==(a=e.promptFeedback)?void 0:a.blockReason,A=(null==M?void 0:M.finishReason)==null&&null!=j,R=null!=(l=null!=(i=null==M?void 0:M.finishReason)?i:j)?l:void 0,N=[],P=null!=(u=null==(s=null==M?void 0:M.content)?void 0:s.parts)?u:[],$=e.usageMetadata;for(let e of P)if("executableCode"in e&&(null==(c=e.executableCode)?void 0:c.code)){let t=this.config.generateId();I=t,N.push({type:"tool-call",toolCallId:t,toolName:null!=(d=null==n?void 0:n.toCustomToolName("code_execution"))?d:"code_execution",input:JSON.stringify(e.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in e&&e.codeExecutionResult)N.push({type:"tool-result",toolCallId:I,toolName:null!=(p=null==n?void 0:n.toCustomToolName("code_execution"))?p:"code_execution",result:{outcome:e.codeExecutionResult.outcome,output:null!=(h=e.codeExecutionResult.output)?h:""}});else if("text"in e&&null!=e.text){let t=e.thoughtSignature?C({thoughtSignature:e.thoughtSignature}):void 0;0===e.text.length?null!=t&&N.length>0&&(N[N.length-1].providerMetadata=t):N.push({type:!0===e.thought?"reasoning":"text",text:e.text,providerMetadata:t})}else if("functionCall"in e&&null!=e.functionCall.name)N.push({type:"tool-call",toolCallId:e.functionCall.id||this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(null!=(g=e.functionCall.args)?g:{}),providerMetadata:e.thoughtSignature?C({thoughtSignature:e.thoughtSignature}):void 0});else if("inlineData"in e){let t=!0===e.thought,o=!!e.thoughtSignature;N.push({type:t?"reasoning-file":"file",data:{type:"data",data:e.inlineData.data},mediaType:e.inlineData.mimeType,providerMetadata:o?C({thoughtSignature:e.thoughtSignature}):void 0})}else if("toolCall"in e&&e.toolCall){let t=e.toolCall.id||this.config.generateId();T=t,N.push({type:"tool-call",toolCallId:t,toolName:`server:${e.toolCall.toolType}`,input:JSON.stringify(null!=(f=e.toolCall.args)?f:{}),providerExecuted:!0,dynamic:!0,providerMetadata:C(e.thoughtSignature?{thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolCall.toolType}:{serverToolCallId:t,serverToolType:e.toolCall.toolType})})}else if("toolResponse"in e&&e.toolResponse){let t=T||e.toolResponse.id||this.config.generateId();N.push({type:"tool-result",toolCallId:t,toolName:`server:${e.toolResponse.toolType}`,result:null!=(y=e.toolResponse.response)?y:{},providerMetadata:C(e.thoughtSignature?{thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolResponse.toolType}:{serverToolCallId:t,serverToolType:e.toolResponse.toolType})}),T=void 0}for(let e of null!=(v=O({groundingMetadata:null==M?void 0:M.groundingMetadata,generateId:this.config.generateId}))?v:[])N.push(e);return{content:N,finishReason:{unified:A?"content-filter":E({finishReason:R,hasToolCalls:N.some(e=>"tool-call"===e.type&&!e.providerExecuted)}),raw:R},usage:m($),warnings:t,providerMetadata:C({promptFeedback:null!=(_=e.promptFeedback)?_:null,groundingMetadata:null!=(b=null==M?void 0:M.groundingMetadata)?b:null,urlContextMetadata:null!=(z=null==M?void 0:M.urlContextMetadata)?z:null,safetyRatings:null!=(w=null==M?void 0:M.safetyRatings)?w:null,usageMetadata:null!=$?$:null,finishMessage:null!=(x=null==M?void 0:M.finishMessage)?x:null,serviceTier:null!=(S=null==$?void 0:$.serviceTier)?S:null}),response:{id:null!=(k=e.responseId)?k:void 0}}}async doGenerate(e){let{args:o,warnings:n,providerOptionsNames:r,extraHeaders:a,toolNameMapping:l}=await this.getArgs(e),s=(0,t.combineHeaders)(this.config.headers?await (0,t.resolve)(this.config.headers):void 0,e.headers,a),{responseHeaders:u,value:c,rawValue:d}=await (0,t.postJsonToApi)({url:`${this.config.baseURL}/${p(this.modelId)}:generateContent`,headers:s,body:o,failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(U),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=this.convertGenerateContentResponse({response:c,warnings:n,providerOptionsNames:r,toolNameMapping:l});return{...m,request:{body:o},response:{...m.response,headers:u,body:d}}}async doStream(e){let o,n,r,a,{args:l,warnings:s,providerOptionsNames:u,extraHeaders:c,toolNameMapping:d}=await this.getArgs(e,{isStreaming:!0}),h=e=>Object.fromEntries(u.map(t=>[t,e])),g=(0,t.combineHeaders)(this.config.headers?await (0,t.resolve)(this.config.headers):void 0,e.headers,c),{responseHeaders:f,value:y}=await (0,t.postJsonToApi)({url:`${this.config.baseURL}/${p(this.modelId)}:streamGenerateContent?alt=sse`,headers:g,body:l,failedResponseHandler:i,successfulResponseHandler:(0,t.createEventSourceResponseHandler)(F),abortSignal:e.abortSignal,fetch:this.config.fetch}),v={unified:"other",raw:void 0},_=null,b=null,z=this.config.generateId,w=!1,x=!1,S=null,I=null,T=0,C=new Set,M=[],j=e=>{let t=M.pop();if(null==t)return;let{finalJSON:o,closingDelta:n}=t.accumulator.finalize();n.length>0&&e.enqueue({type:"tool-input-delta",id:t.toolCallId,delta:n,providerMetadata:t.providerMetadata}),e.enqueue({type:"tool-input-end",id:t.toolCallId,providerMetadata:t.providerMetadata}),e.enqueue({type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:o,providerMetadata:t.providerMetadata}),w=!0};return{stream:y.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:s})},transform(t,i){var l,s,u,c,p,m,g,f,y,A,R,N,P,$,q,L,D;if(e.includeRawChunks&&i.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void i.enqueue({type:"error",error:t.error});let U=t.value;x||null==U.responseId||(x=!0,i.enqueue({type:"response-metadata",id:U.responseId}));let F=U.usageMetadata;null!=F&&(r=F);let H=null==(l=U.candidates)?void 0:l[0];if(null==H){let e=null==(s=U.promptFeedback)?void 0:s.blockReason;null!=e&&(v={unified:"content-filter",raw:e},a=h({promptFeedback:null!=(u=U.promptFeedback)?u:null,groundingMetadata:_,urlContextMetadata:b,safetyRatings:null,usageMetadata:null!=F?F:null,finishMessage:null,serviceTier:null!=(c=null==r?void 0:r.serviceTier)?c:null}));return}let B=H.content;null!=H.groundingMetadata&&(_=H.groundingMetadata),null!=H.urlContextMetadata&&(b=H.urlContextMetadata);let V=O({groundingMetadata:H.groundingMetadata,generateId:z});if(null!=V)for(let e of V)"url"!==e.sourceType||C.has(e.url)||(C.add(e.url),i.enqueue(e));if(null!=B){let e=null!=(p=B.parts)?p:[];for(let t of e)if("executableCode"in t&&(null==(m=t.executableCode)?void 0:m.code)){let e=z();o=e,i.enqueue({type:"tool-call",toolCallId:e,toolName:d.toCustomToolName("code_execution"),input:JSON.stringify(t.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in t&&t.codeExecutionResult){let e=o;e&&i.enqueue({type:"tool-result",toolCallId:e,toolName:d.toCustomToolName("code_execution"),result:{outcome:t.codeExecutionResult.outcome,output:null!=(g=t.codeExecutionResult.output)?g:""}})}else if("text"in t&&null!=t.text){let e=t.thoughtSignature?h({thoughtSignature:t.thoughtSignature}):void 0;0===t.text.length?null!=e&&null!==S&&i.enqueue({type:"text-delta",id:S,delta:"",providerMetadata:e}):!0===t.thought?(null!==S&&(i.enqueue({type:"text-end",id:S}),S=null),null===I&&(I=String(T++),i.enqueue({type:"reasoning-start",id:I,providerMetadata:e})),i.enqueue({type:"reasoning-delta",id:I,delta:t.text,providerMetadata:e})):(null!==I&&(i.enqueue({type:"reasoning-end",id:I}),I=null),null===S&&(S=String(T++),i.enqueue({type:"text-start",id:S,providerMetadata:e})),i.enqueue({type:"text-delta",id:S,delta:t.text,providerMetadata:e}))}else if("inlineData"in t){null!==S&&(i.enqueue({type:"text-end",id:S}),S=null),null!==I&&(i.enqueue({type:"reasoning-end",id:I}),I=null);let e=!0===t.thought,o=t.thoughtSignature?h({thoughtSignature:t.thoughtSignature}):void 0;i.enqueue({type:e?"reasoning-file":"file",mediaType:t.inlineData.mimeType,data:{type:"data",data:t.inlineData.data},providerMetadata:o})}else if("toolCall"in t&&t.toolCall){let e=t.toolCall.id||z();n=e;let o=h({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolCall.toolType});i.enqueue({type:"tool-call",toolCallId:e,toolName:`server:${t.toolCall.toolType}`,input:JSON.stringify(null!=(f=t.toolCall.args)?f:{}),providerExecuted:!0,dynamic:!0,providerMetadata:o})}else if("toolResponse"in t&&t.toolResponse){let e=n||t.toolResponse.id||z(),o=h({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolResponse.toolType});i.enqueue({type:"tool-result",toolCallId:e,toolName:`server:${t.toolResponse.toolType}`,result:null!=(y=t.toolResponse.response)?y:{},providerMetadata:o}),n=void 0}for(let t of e){if(!("functionCall"in t))continue;let e=t.thoughtSignature?h({thoughtSignature:t.thoughtSignature}):void 0,o=null!=t.functionCall.partialArgs||null!=t.functionCall.name&&!0===t.functionCall.willContinue,n=null==t.functionCall.name&&null==t.functionCall.args&&null==t.functionCall.partialArgs&&null==t.functionCall.willContinue,r=null!=t.functionCall.name&&null!=t.functionCall.args&&null==t.functionCall.partialArgs,a=null!=t.functionCall.name&&null==t.functionCall.args&&null==t.functionCall.partialArgs&&!0!==t.functionCall.willContinue;if(o){if(null!=t.functionCall.name){let o=t.functionCall.id||z(),n=new k;if(M.push({toolCallId:o,toolName:t.functionCall.name,accumulator:n,providerMetadata:e}),i.enqueue({type:"tool-input-start",id:o,toolName:t.functionCall.name,providerMetadata:e}),null!=t.functionCall.partialArgs){let r=t.functionCall.partialArgs,{textDelta:a}=n.processPartialArgs(r);a.length>0&&i.enqueue({type:"tool-input-delta",id:o,delta:a,providerMetadata:e}),!0!==t.functionCall.willContinue&&r.every(e=>!0!==e.willContinue)&&j(i)}}else if(null!=t.functionCall.partialArgs&&M.length>0){let o=M[M.length-1],n=t.functionCall.partialArgs,{textDelta:r}=o.accumulator.processPartialArgs(n);r.length>0&&i.enqueue({type:"tool-input-delta",id:o.toolCallId,delta:r,providerMetadata:e}),!0!==t.functionCall.willContinue&&n.every(e=>!0!==e.willContinue)&&j(i)}}else if(n&&M.length>0)j(i);else if(r){let o=t.functionCall.id||z(),n=t.functionCall.name,r="string"==typeof t.functionCall.args?t.functionCall.args:JSON.stringify(null!=(A=t.functionCall.args)?A:{});i.enqueue({type:"tool-input-start",id:o,toolName:n,providerMetadata:e}),i.enqueue({type:"tool-input-delta",id:o,delta:r,providerMetadata:e}),i.enqueue({type:"tool-input-end",id:o,providerMetadata:e}),i.enqueue({type:"tool-call",toolCallId:o,toolName:n,input:r,providerMetadata:e}),w=!0}else if(a){let o=t.functionCall.id||z(),n=t.functionCall.name;i.enqueue({type:"tool-input-start",id:o,toolName:n,providerMetadata:e}),i.enqueue({type:"tool-input-end",id:o,providerMetadata:e}),i.enqueue({type:"tool-call",toolCallId:o,toolName:n,input:"{}",providerMetadata:e}),w=!0}}}let J=null==(R=U.promptFeedback)?void 0:R.blockReason,W=null==H.finishReason&&null!=J,K=null!=(P=null!=(N=H.finishReason)?N:J)?P:void 0;null!=K&&(v={unified:W?"content-filter":E({finishReason:K,hasToolCalls:w}),raw:K},a=h({promptFeedback:null!=($=U.promptFeedback)?$:null,groundingMetadata:_,urlContextMetadata:b,safetyRatings:null!=(q=H.safetyRatings)?q:null,usageMetadata:null!=F?F:null,finishMessage:null!=(L=H.finishMessage)?L:null,serviceTier:null!=(D=null==r?void 0:r.serviceTier)?D:null}))},flush(e){null!==S&&e.enqueue({type:"text-end",id:S}),null!==I&&e.enqueue({type:"reasoning-end",id:I}),e.enqueue({type:"finish",finishReason:v,usage:m(r),providerMetadata:a})}})),response:{headers:f},request:{body:l}}}};function O({groundingMetadata:e,generateId:t}){var o,n,r,a,i,l;if(!(null==e?void 0:e.groundingChunks))return;let s=[];for(let u of e.groundingChunks)if(null!=u.web)s.push({type:"source",sourceType:"url",id:t(),url:u.web.uri,title:null!=(o=u.web.title)?o:void 0});else if(null!=u.image)s.push({type:"source",sourceType:"url",id:t(),url:u.image.sourceUri,title:null!=(n=u.image.title)?n:void 0});else if(null!=u.retrievedContext){let e=u.retrievedContext.uri,o=u.retrievedContext.fileSearchStore;if(e&&(e.startsWith("http://")||e.startsWith("https://")))s.push({type:"source",sourceType:"url",id:t(),url:e,title:null!=(r=u.retrievedContext.title)?r:void 0});else if(e){let o,n=null!=(a=u.retrievedContext.title)?a:"Unknown Document",r="application/octet-stream";e.endsWith(".pdf")?r="application/pdf":e.endsWith(".txt")?r="text/plain":e.endsWith(".docx")?r="application/vnd.openxmlformats-officedocument.wordprocessingml.document":e.endsWith(".doc")?r="application/msword":e.match(/\.(md|markdown)$/)&&(r="text/markdown"),o=e.split("/").pop(),s.push({type:"source",sourceType:"document",id:t(),mediaType:r,title:n,filename:o})}else if(o){let e=null!=(i=u.retrievedContext.title)?i:"Unknown Document";s.push({type:"source",sourceType:"document",id:t(),mediaType:"application/octet-stream",title:e,filename:o.split("/").pop()})}}else null!=u.maps&&u.maps.uri&&s.push({type:"source",sourceType:"url",id:t(),url:u.maps.uri,title:null!=(l=u.maps.title)?l:void 0});return s.length>0?s:void 0}var R=()=>r.z.object({webSearchQueries:r.z.array(r.z.string()).nullish(),imageSearchQueries:r.z.array(r.z.string()).nullish(),retrievalQueries:r.z.array(r.z.string()).nullish(),searchEntryPoint:r.z.object({renderedContent:r.z.string()}).nullish(),groundingChunks:r.z.array(r.z.object({web:r.z.object({uri:r.z.string(),title:r.z.string().nullish()}).nullish(),image:r.z.object({sourceUri:r.z.string(),imageUri:r.z.string(),title:r.z.string().nullish(),domain:r.z.string().nullish()}).nullish(),retrievedContext:r.z.object({uri:r.z.string().nullish(),title:r.z.string().nullish(),text:r.z.string().nullish(),fileSearchStore:r.z.string().nullish()}).nullish(),maps:r.z.object({uri:r.z.string().nullish(),title:r.z.string().nullish(),text:r.z.string().nullish(),placeId:r.z.string().nullish()}).nullish()})).nullish(),groundingSupports:r.z.array(r.z.object({segment:r.z.object({startIndex:r.z.number().nullish(),endIndex:r.z.number().nullish(),text:r.z.string().nullish()}).nullish(),segment_text:r.z.string().nullish(),groundingChunkIndices:r.z.array(r.z.number()).nullish(),supportChunkIndices:r.z.array(r.z.number()).nullish(),confidenceScores:r.z.array(r.z.number()).nullish(),confidenceScore:r.z.array(r.z.number()).nullish()})).nullish(),retrievalMetadata:r.z.union([r.z.object({webDynamicRetrievalScore:r.z.number()}),r.z.object({})]).nullish()}),N=r.z.object({jsonPath:r.z.string(),stringValue:r.z.string().nullish(),numberValue:r.z.number().nullish(),boolValue:r.z.boolean().nullish(),nullValue:r.z.unknown().nullish(),willContinue:r.z.boolean().nullish()}),P=()=>r.z.object({parts:r.z.array(r.z.union([r.z.object({functionCall:r.z.object({id:r.z.string().nullish(),name:r.z.string().nullish(),args:r.z.unknown().nullish(),partialArgs:r.z.array(N).nullish(),willContinue:r.z.boolean().nullish()}),thoughtSignature:r.z.string().nullish()}),r.z.object({inlineData:r.z.object({mimeType:r.z.string(),data:r.z.string()}),thought:r.z.boolean().nullish(),thoughtSignature:r.z.string().nullish()}),r.z.object({toolCall:r.z.object({toolType:r.z.string(),args:r.z.unknown().nullish(),id:r.z.string()}),thoughtSignature:r.z.string().nullish()}),r.z.object({toolResponse:r.z.object({toolType:r.z.string(),response:r.z.unknown().nullish(),id:r.z.string()}),thoughtSignature:r.z.string().nullish()}),r.z.object({executableCode:r.z.object({language:r.z.string(),code:r.z.string()}).nullish(),codeExecutionResult:r.z.object({outcome:r.z.string(),output:r.z.string().nullish()}).nullish(),text:r.z.string().nullish(),thought:r.z.boolean().nullish(),thoughtSignature:r.z.string().nullish()})])).nullish()}),$=()=>r.z.object({category:r.z.string().nullish(),probability:r.z.string().nullish(),probabilityScore:r.z.number().nullish(),severity:r.z.string().nullish(),severityScore:r.z.number().nullish(),blocked:r.z.boolean().nullish()}),q=r.z.array(r.z.object({modality:r.z.string(),tokenCount:r.z.number()}).loose()).nullish(),L=r.z.object({cachedContentTokenCount:r.z.number().nullish(),thoughtsTokenCount:r.z.number().nullish(),promptTokenCount:r.z.number().nullish(),candidatesTokenCount:r.z.number().nullish(),toolUsePromptTokenCount:r.z.number().nullish(),totalTokenCount:r.z.number().nullish(),trafficType:r.z.string().nullish(),serviceTier:r.z.string().nullish(),promptTokensDetails:q,cacheTokensDetails:q,candidatesTokensDetails:q,toolUsePromptTokensDetails:q}).loose(),D=()=>r.z.object({urlMetadata:r.z.array(r.z.object({retrievedUrl:r.z.string(),urlRetrievalStatus:r.z.string()})).nullish()}),U=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({responseId:r.z.string().nullish(),candidates:r.z.array(r.z.object({content:P().nullish().or(r.z.object({}).strict()),finishReason:r.z.string().nullish(),finishMessage:r.z.string().nullish(),safetyRatings:r.z.array($()).nullish(),groundingMetadata:R().nullish(),urlContextMetadata:D().nullish()})).nullish(),usageMetadata:L.nullish(),promptFeedback:r.z.object({blockReason:r.z.string().nullish(),safetyRatings:r.z.array($()).nullish()}).nullish()}))),F=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({responseId:r.z.string().nullish(),candidates:r.z.array(r.z.object({content:P().nullish(),finishReason:r.z.string().nullish(),finishMessage:r.z.string().nullish(),safetyRatings:r.z.array($()).nullish(),groundingMetadata:R().nullish(),urlContextMetadata:D().nullish()})).nullish(),usageMetadata:L.nullish(),promptFeedback:r.z.object({blockReason:r.z.string().nullish(),safetyRatings:r.z.array($()).nullish()}).nullish()}))),H=new Set(["text","reasoning","source","tool-call","tool-result"]),B=r.z.object({code:r.z.union([r.z.number(),r.z.string()]).nullish(),message:r.z.string().nullish(),status:r.z.string().nullish()}),V=r.z.object({requestCount:r.z.union([r.z.string(),r.z.number()]).nullish(),successfulRequestCount:r.z.union([r.z.string(),r.z.number()]).nullish(),failedRequestCount:r.z.union([r.z.string(),r.z.number()]).nullish(),pendingRequestCount:r.z.union([r.z.string(),r.z.number()]).nullish()}),J=r.z.object({responsesFile:r.z.string().nullish(),inlinedResponses:r.z.object({inlinedResponses:r.z.array(r.z.object({metadata:r.z.object({key:r.z.string()}),response:r.z.unknown().nullish(),error:B.nullish()}))}).nullish()}),W=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({name:r.z.string(),metadata:r.z.object({state:r.z.string().nullish(),createTime:r.z.string().nullish(),batchStats:V.nullish(),output:J.nullish()}).nullish(),done:r.z.boolean().nullish(),error:B.nullish(),response:J.nullish()}))),K=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({file:r.z.object({name:r.z.string(),expirationTime:r.z.string().nullish()})}))),G=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({key:r.z.string(),response:r.z.unknown().nullish(),error:B.nullish()}))),Y=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({candidates:r.z.array(r.z.unknown()).nullish(),promptFeedback:r.z.object({blockReason:r.z.string().nullish()}).nullish()}))),X=class e extends A{static[n.WORKFLOW_SERIALIZE](e){return A[n.WORKFLOW_SERIALIZE](e)}static[n.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,t.config)}constructor(e,o){var n;super(e,o),this.batchConfig=o,this.batchGenerateId=null!=(n=o.generateId)?n:t.generateId}async experimental_doStartBatch(e){let n,r=[],a=`ai-sdk-batch-${this.batchGenerateId()}`,l=[],s={batch:{displayName:a,...null!=e.webhookUrl&&{webhookConfig:{uris:[e.webhookUrl]}},inputConfig:{requests:{requests:l}}}},u=new TextEncoder,c=u.encode(JSON.stringify(s)).byteLength;for(let t of e.requests){let e=await this.getArgs(t.options),o={request:e.args,metadata:{key:t.id}};if(null==n){let r=c+u.encode(JSON.stringify(o)).byteLength+ +(l.length>0);if(r<2e7)l.push(o),c=r;else{for(let e of(n=[],l))n.push(JSON.stringify({key:e.metadata.key,request:e.request}),"\n");l.length=0,n.push(JSON.stringify({key:t.id,request:e.args}),"\n")}}else n.push(JSON.stringify({key:t.id,request:e.args}),"\n");for(let o of e.warnings)r.push({requestId:t.id,warning:o})}let d=await this.getHeaders(e.headers),m=`${this.batchConfig.baseURL}/${p(this.modelId)}:batchGenerateContent`;if(null==n){let{value:o}=await (0,t.postJsonToApi)({url:m,headers:d,body:s,failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(W),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch});return{batchId:o.name,...Z(o),warnings:r}}let h=new Blob(n,{type:"application/jsonl"});if(n.length=0,h.size>0x80000000)throw new o.InvalidArgumentError({argument:"requests",message:"Google batch input files must not exceed 2 GB."});let{value:g}=await (0,t.postJsonToApi)({url:`${this.getBaseOrigin()}/upload/v1beta/files`,headers:(0,t.combineHeaders)(d,{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(h.size),"X-Goog-Upload-Header-Content-Type":"application/jsonl"}),body:{file:{display_name:`${a}-input`}},failedResponseHandler:i,successfulResponseHandler:et,abortSignal:e.abortSignal,fetch:this.batchConfig.fetch}),{value:f}=await (0,t.postToApi)({url:g,headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize","Content-Type":"application/jsonl"},body:{content:h,values:{byteLength:h.size,mediaType:"application/jsonl"}},failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(K),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch}),{value:y}=await (0,t.postJsonToApi)({url:m,headers:d,body:{batch:{displayName:a,...null!=e.webhookUrl&&{webhookConfig:{uris:[e.webhookUrl]}},inputConfig:{fileName:f.file.name}}},failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(W),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch});return{batchId:y.name,...Z(y),providerMetadata:{google:{inputFileId:f.file.name,...null!=f.file.expirationTime?{inputFileExpiresAt:f.file.expirationTime}:{}}},warnings:r}}async experimental_doGetBatchStatus(e){return Z(await this.retrieveBatch(e))}async experimental_doGetBatchResults(e){var n,r,a,l,s,u,c,d,p,m;let h=await this.retrieveBatch(e),g=Z(h);if("pending"===g.status)throw new o.InvalidArgumentError({argument:"batchId",message:`Google batch "${e.batchId}" is not complete.`});let f=null!=(u=null==(a=null==(r=null==(n=h.metadata)?void 0:n.output)?void 0:r.inlinedResponses)?void 0:a.inlinedResponses)?u:null==(s=null==(l=h.response)?void 0:l.inlinedResponses)?void 0:s.inlinedResponses;if(null!=f)return(0,t.convertAsyncIteratorToReadableStream)(this.iterateBatchResults(f.map(e=>({key:e.metadata.key,response:e.response,error:e.error}))));let y=null!=(m=null==(d=null==(c=h.metadata)?void 0:c.output)?void 0:d.responsesFile)?m:null==(p=h.response)?void 0:p.responsesFile;if(null==y){if("completed"===g.status)throw new o.InvalidResponseDataError({data:h,message:`Google batch "${e.batchId}" completed without batch output.`});return new ReadableStream({start(e){e.close()}})}let v=y.split("/").map(e=>encodeURIComponent(e)).join("/"),{value:_}=await (0,t.getFromApi)({url:`${this.getBaseOrigin()}/download/v1beta/${v}:download?alt=media`,headers:await this.getHeaders(e.headers),failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonLinesResponseHandler)(G),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return(0,t.convertAsyncIteratorToReadableStream)(this.iterateBatchResults(_))}async retrieveBatch(e){let{value:o}=await (0,t.getFromApi)({url:`${this.batchConfig.baseURL}/${e.batchId}`,headers:await this.getHeaders(e.headers),failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(W),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return o}async *iterateBatchResults(e){var o,n,r;for await(let a of e){if(null!=a.error){let e=ee(a.error,"Google batch request failed."),t="CANCELLED"===a.error.status||"1"===String(a.error.code)?"cancelled":"failed";yield{id:a.key,status:t,error:e};continue}if(null==a.response){yield{id:a.key,status:"failed",error:{message:"Google returned a batch result without a response or error.",code:"invalid_batch_result"}};continue}let e=await (0,t.safeValidateTypes)({value:a.response,schema:Y});if(e.success&&(null==e.value.candidates||0===e.value.candidates.length)){let t=null!=(o=e.value.promptFeedback)?o:void 0,i=null!=(n=null==t?void 0:t.blockReason)?n:void 0;yield{id:a.key,status:"failed",error:{message:null==i?"Google returned a batch response without any candidates.":`Google blocked the batch request (${i}).`,code:null==i?"invalid_response":"prompt_blocked",...null!=i?{type:i}:{}},...null!=t?{providerMetadata:{google:{promptFeedback:{blockReason:null!=(r=t.blockReason)?r:null}}}}:{}};continue}let i=await (0,t.safeValidateTypes)({value:a.response,schema:U});if(!i.success){yield{id:a.key,status:"failed",error:{message:"Google returned an invalid GenerateContent batch result.",code:"invalid_response"}};continue}let l=this.convertGenerateContentResponse({response:i.value,warnings:[],providerOptionsNames:["google"]}),s=l.content.find(e=>!H.has(e.type));if(null!=s){yield{id:a.key,status:"failed",error:{message:`Google returned a "${s.type}" content block, but that content is not supported in AI SDK text batches.`,code:"unsupported_content"}};continue}yield{id:a.key,status:"succeeded",result:l}}}async getHeaders(e){return(0,t.combineHeaders)(this.batchConfig.headers?await (0,t.resolve)(this.batchConfig.headers):void 0,e)}getBaseOrigin(){return this.batchConfig.baseURL.replace(/\/v1beta$/,"")}};function Z(e){var o,n,r,a,i,l,s,u,c,d;let p,m,h,g,f=null!=(n=null==(o=e.metadata)?void 0:o.state)?n:void 0,y=(p=Q(null==(s=null==(r=e.metadata)?void 0:r.batchStats)?void 0:s.requestCount),m=Q(null!=(u=null==s?void 0:s.successfulRequestCount)?u:0),h=Q(null!=(c=null==s?void 0:s.failedRequestCount)?c:0),g=Q(null!=(d=null==s?void 0:s.pendingRequestCount)?d:0),(0,t.normalizeBatchRequestCounts)({total:p,pending:g,completed:m,failed:h})),v=null!=(i=null==(a=e.metadata)?void 0:a.createTime)?i:void 0,_=null!=e.error?ee(e.error,"Google batch failed."):void 0;return{status:function({rawStatus:e,done:t,hasError:o}){if(o)return"failed";if(null==e)return t?"completed":"pending";switch(e.replace(/^(?:BATCH|JOB)_STATE_/,"")){case"SUCCEEDED":return"completed";case"FAILED":case"CANCELLED":case"EXPIRED":return"failed";default:return"pending"}}({rawStatus:f,done:null!=(l=e.done)?l:void 0,hasError:null!=_}),...null!=f?{rawStatus:f}:{},...null!=y?{requestCounts:y}:{},...null!=_?{error:_}:{},...null!=v?{createdAt:v}:{}}}function Q(e){let t="string"==typeof e&&/^\d+$/.test(e)?Number(e):e;return"number"==typeof t&&Number.isSafeInteger(t)&&t>=0?t:void 0}function ee(e,t){var o;return{message:null!=(o=e.message)?o:t,...null!=e.status?{type:e.status}:{},...null!=e.code?{code:String(e.code)}:{}}}var et=async({response:e})=>{let t=e.headers.get("x-goog-upload-url");if(null==t)throw new o.InvalidResponseDataError({data:e.headers,message:"Google did not return a resumable upload URL."});return{value:t}},eo=(0,t.createProviderExecutedToolFactory)({id:"google.code_execution",inputSchema:r.z.object({language:r.z.string().describe("The programming language of the code."),code:r.z.string().describe("The code to be executed.")}),outputSchema:r.z.object({outcome:r.z.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:r.z.string().describe("The output from the code execution.")})}),en=(0,t.createProviderExecutedToolFactory)({id:"google.enterprise_web_search",inputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({}))),outputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({})))});r.z.looseObject({fileSearchStoreNames:r.z.array(r.z.string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:r.z.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:r.z.string().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()});var er=(0,t.createProviderExecutedToolFactory)({id:"google.file_search",inputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({}))),outputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({})))}),ea=(0,t.createProviderExecutedToolFactory)({id:"google.google_maps",inputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({}))),outputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({})))}),ei=r.z.looseObject({searchTypes:r.z.object({webSearch:r.z.object({}).optional(),imageSearch:r.z.object({}).optional()}).optional(),timeRangeFilter:r.z.object({startTime:r.z.string(),endTime:r.z.string()}).optional()}),el=(0,t.createProviderExecutedToolFactory)({id:"google.google_search",inputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({}))),outputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({})))}),es={googleSearch:el,enterpriseWebSearch:en,googleMaps:ea,urlContext:(0,t.createProviderExecutedToolFactory)({id:"google.url_context",inputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({}))),outputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({})))}),fileSearch:er,codeExecution:eo,vertexRagStore:(0,t.createProviderExecutedToolFactory)({id:"google.vertex_rag_store",inputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({}))),outputSchema:(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({})))})},eu=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({googleSearch:ei.optional()}))),ec=class e{constructor(e,t,o){this.modelId=e,this.settings=t,this.config=o,this.specificationVersion="v4"}static[n.WORKFLOW_SERIALIZE](e){return(0,t.serializeModelOptions)({modelId:e.modelId,config:e.config})}static[n.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,{},t.config)}get maxImagesPerCall(){return null!=this.settings.maxImagesPerCall?this.settings.maxImagesPerCall:10}get provider(){return this.config.provider}async doGenerate(e){var o,n,r,a,i,l,s,u,c,d,p;if(!this.modelId.startsWith("gemini-"))throw Error("Google image models other than Gemini are no longer supported. Use a model ID that starts with `gemini-`.");let{prompt:m,n:h,size:g,aspectRatio:f,seed:y,providerOptions:v,headers:_,abortSignal:b,files:z,mask:w}=e,x=[];if(null!=w)throw Error("Gemini image models do not support mask-based image editing.");if(null!=h&&h>1)throw Error("Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.");null!=g&&x.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let S=[];if(null!=m&&S.push({type:"text",text:m}),null!=z&&z.length>0)for(let e of z)"url"===e.type?S.push({type:"file",data:{type:"url",url:new URL(e.url)},mediaType:"image/*"}):S.push({type:"file",data:{type:"data",data:"string"==typeof e.data?e.data:new Uint8Array(e.data)},mediaType:e.mediaType});let k=[{role:"user",content:S}],I=await (0,t.parseProviderOptions)({provider:"google",providerOptions:v,schema:eu}),{googleSearch:T,responseModalities:C,imageConfig:E,...M}=null!=(o=null==v?void 0:v.google)?o:{},j=new A(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:null!=(n=this.config.headers)?n:{},fetch:this.config.fetch,generateId:null!=(r=this.config.generateId)?r:t.generateId}),O=await j.doGenerate({prompt:k,seed:y,providerOptions:{google:{...M,responseModalities:["IMAGE"],imageConfig:null!=f||null!=E?{...E,...null!=f?{aspectRatio:f}:{}}:void 0}},tools:(null==I?void 0:I.googleSearch)!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:I.googleSearch}]:void 0,headers:_,abortSignal:b}),R=null!=(l=null==(i=null==(a=this.config._internal)?void 0:a.currentDate)?void 0:i.call(a))?l:new Date,N=[];for(let e of O.content)"file"===e.type&&e.mediaType.startsWith("image/")&&"data"===e.data.type&&N.push((0,t.convertToBase64)(e.data.data));return{images:N,warnings:x,providerMetadata:{google:{...null!=(u=null==(s=O.providerMetadata)?void 0:s.google)?u:{},images:N.map(()=>({}))}},response:{timestamp:R,modelId:this.modelId,headers:null==(c=O.response)?void 0:c.headers},usage:O.usage?{inputTokens:O.usage.inputTokens.total,outputTokens:O.usage.outputTokens.total,totalTokens:(null!=(d=O.usage.inputTokens.total)?d:0)+(null!=(p=O.usage.outputTokens.total)?p:0)}:void 0}}};function ed(e){let t=encodeURIComponent(e);return"."===t?"%252E":".."===t?"%252E%252E":t}var ep=class{constructor(e){this.config=e,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadFile(e){var n,r,a,l,s;let u=await (0,t.parseProviderOptions)({provider:"google",providerOptions:e.providerOptions,schema:eh}),c=(0,t.combineHeaders)(this.config.headers(),e.headers),d=null!=(n=this.config.fetch)?n:globalThis.fetch,p=[];null!=e.filename&&p.push({type:"unsupported",feature:"filename"});let m=(0,t.convertInlineFileDataToUint8Array)(e.data),h=e.mediaType,g=null==u?void 0:u.displayName,f=this.config.baseURL.replace(/\/v1beta$/,""),y=await d(`${f}/upload/v1beta/files`,{method:"POST",headers:{...c,"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(m.length),"X-Goog-Upload-Header-Content-Type":h,"Content-Type":"application/json"},body:JSON.stringify({file:{...null!=g?{display_name:g}:{}}}),signal:e.abortSignal});if(!y.ok){let e=await y.text();throw new o.AISDKError({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to initiate resumable upload: ${y.status} ${e}`})}let v=y.headers.get("x-goog-upload-url");if(!v)throw new o.AISDKError({name:"GOOGLE_FILES_UPLOAD_ERROR",message:"No upload URL returned from initiation request"});let _=await d(v,{method:"POST",headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"},body:(s=m).buffer instanceof ArrayBuffer?s:new Uint8Array(s),signal:e.abortSignal});if(!_.ok){let e=await _.text();throw new o.AISDKError({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to upload file data: ${_.status} ${e}`})}let b=(await _.json()).file,z=null!=(r=null==u?void 0:u.pollIntervalMs)?r:2e3,w=null!=(a=null==u?void 0:u.pollTimeoutMs)?a:3e5,x=Date.now();for(;"PROCESSING"===b.state;){if(Date.now()-x>w)throw new o.AISDKError({name:"GOOGLE_FILES_UPLOAD_TIMEOUT",message:`File processing timed out after ${w}ms`});await (0,t.delay)(z,{abortSignal:e.abortSignal});let n=/^files\/([^/]+)$/.exec(b.name),r=null!=n?`files/${ed(n[1])}`:ed(b.name),{value:a}=await (0,t.getFromApi)({url:`${this.config.baseURL}/${r}`,validateUrl:!1,headers:(0,t.combineHeaders)(c),successfulResponseHandler:(0,t.createJsonResponseHandler)(em),failedResponseHandler:i,abortSignal:e.abortSignal,fetch:this.config.fetch});b=a}if("FAILED"===b.state)throw new o.AISDKError({name:"GOOGLE_FILES_UPLOAD_FAILED",message:`File processing failed for ${b.name}`});return{warnings:p,providerReference:{google:b.uri},mediaType:null!=(l=b.mimeType)?l:e.mediaType,providerMetadata:{google:{name:b.name,displayName:b.displayName,mimeType:b.mimeType,sizeBytes:b.sizeBytes,state:b.state,uri:b.uri,...null!=b.createTime?{createTime:b.createTime}:{},...null!=b.updateTime?{updateTime:b.updateTime}:{},...null!=b.expirationTime?{expirationTime:b.expirationTime}:{},...null!=b.sha256Hash?{sha256Hash:b.sha256Hash}:{}}}}}},em=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({name:r.z.string(),displayName:r.z.string().nullish(),mimeType:r.z.string(),sizeBytes:r.z.string().nullish(),createTime:r.z.string().nullish(),updateTime:r.z.string().nullish(),expirationTime:r.z.string().nullish(),sha256Hash:r.z.string().nullish(),uri:r.z.string(),state:r.z.string()}))),eh=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.looseObject({displayName:r.z.string().nullish(),pollIntervalMs:r.z.number().positive().nullish(),pollTimeoutMs:r.z.number().positive().nullish()}))),eg=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.looseObject({pollIntervalMs:r.z.number().positive().nullish(),pollTimeoutMs:r.z.number().positive().nullish(),personGeneration:r.z.enum(["dont_allow","allow_adult","allow_all"]).nullish(),negativePrompt:r.z.string().nullish(),referenceImages:r.z.array(r.z.object({bytesBase64Encoded:r.z.string().nullish(),gcsUri:r.z.string().nullish()})).nullish()})));function ef(e,o){return"url"===e.type?e.url.startsWith("gs://")?{gcsUri:e.url,mimeType:"image/png"}:void o.push({type:"unsupported",feature:"URL-based image input",details:"Google Generative AI video models require base64-encoded images or GCS URIs. URL will be ignored."}):{bytesBase64Encoded:"string"==typeof e.data?e.data:(0,t.convertUint8ArrayToBase64)(e.data),mimeType:e.mediaType||"image/png"}}var ey=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v4"}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async buildRequest(e){var o,n,r,a,i,l;let s=[],u=await (0,t.parseProviderOptions)({provider:"google",providerOptions:e.providerOptions,schema:eg}),c=[{}],d=c[0];null!=e.prompt&&(d.prompt=e.prompt);let p=null!=(a=null==(l=null==(i=(r=e).frameImages)?void 0:i.find(e=>"first_frame"===e.frameType))?void 0:l.image)?a:r.image;if(null!=p){let e=ef(p,s);null!=e&&(d.image=e)}let m=null==(n=null==(o=e.frameImages)?void 0:o.find(e=>"last_frame"===e.frameType))?void 0:n.image;if(null!=m){let e=ef(m,s);null!=e&&(d.lastFrame=e)}let h=function(e){if(null==e.frameImages||!(e.frameImages.length>0))return null!=e.inputReferences&&e.inputReferences.length>0?e.inputReferences:void 0}(e);null!=h?d.referenceImages=h.flatMap(e=>{let t,o=null!=(t=ef(e,s))?{image:t,referenceType:"asset"}:void 0;return null!=o?[o]:[]}):(null==u?void 0:u.referenceImages)!=null&&(d.referenceImages=u.referenceImages.map(e=>e.bytesBase64Encoded?{image:{bytesBase64Encoded:e.bytesBase64Encoded,mimeType:"image/png"},referenceType:"asset"}:e.gcsUri?{image:{gcsUri:e.gcsUri,mimeType:"image/png"},referenceType:"asset"}:e));let g={sampleCount:e.n};if(e.aspectRatio&&(g.aspectRatio=e.aspectRatio),e.resolution&&(g.resolution=({"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"})[e.resolution]||e.resolution),e.duration&&(g.durationSeconds=e.duration),e.seed&&(g.seed=e.seed),null!=u)for(let[e,t]of(void 0!==u.personGeneration&&null!==u.personGeneration&&(g.personGeneration=u.personGeneration),void 0!==u.negativePrompt&&null!==u.negativePrompt&&(g.negativePrompt=u.negativePrompt),Object.entries(u)))["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","referenceImages"].includes(e)||(g[e]=t);return{instances:c,parameters:g,warnings:s,googleOptions:u}}async buildCompletedResult(e,n,r,a){var i,l;let s=e.response;if(!(null==(i=null==s?void 0:s.generateVideoResponse)?void 0:i.generatedSamples)||0===s.generateVideoResponse.generatedSamples.length)throw new o.AISDKError({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:`No videos in response. Response: ${JSON.stringify(e)}`});let u=[],c=[],d=await (0,t.resolve)(this.config.headers),p=null==d?void 0:d["x-goog-api-key"];for(let e of s.generateVideoResponse.generatedSamples)if(null==(l=e.video)?void 0:l.uri){let o=p&&(0,t.isSameOrigin)(e.video.uri,this.config.baseURL)?`${e.video.uri}${e.video.uri.includes("?")?"&":"?"}key=${p}`:e.video.uri;u.push({type:"url",url:o,mediaType:"video/mp4"}),c.push({uri:e.video.uri})}if(0===u.length)throw new o.AISDKError({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{status:"completed",videos:u,warnings:r,response:{timestamp:a,modelId:this.modelId,headers:n},providerMetadata:{google:{videos:c}}}}async doStart(e){var n,r,a;let l=null!=(a=null==(r=null==(n=this.config._internal)?void 0:n.currentDate)?void 0:r.call(n))?a:new Date,{instances:s,parameters:u,warnings:c}=await this.buildRequest(e),{value:d,responseHeaders:p}=await (0,t.postJsonToApi)({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:(0,t.combineHeaders)(await (0,t.resolve)(this.config.headers),e.headers),body:{instances:s,parameters:u},successfulResponseHandler:(0,t.createJsonResponseHandler)(ev),failedResponseHandler:i,abortSignal:e.abortSignal,fetch:this.config.fetch}),m=d.name;if(!m)throw new o.AISDKError({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No operation name returned from API"});return{operation:{operationName:m},warnings:c,response:{timestamp:l,modelId:this.modelId,headers:p}}}async doStatus(e){var o,n,r;let a=null!=(r=null==(n=null==(o=this.config._internal)?void 0:o.currentDate)?void 0:n.call(o))?r:new Date,{operationName:l}=e.operation,{value:s,responseHeaders:u}=await (0,t.getFromApi)({url:`${this.config.baseURL}/${l}`,validateUrl:!1,headers:(0,t.combineHeaders)(await (0,t.resolve)(this.config.headers),e.headers),successfulResponseHandler:(0,t.createJsonResponseHandler)(ev),failedResponseHandler:i,abortSignal:e.abortSignal,fetch:this.config.fetch});return s.done?s.error?{status:"error",error:`Video generation failed: ${s.error.message}`,response:{timestamp:a,modelId:this.modelId,headers:u}}:this.buildCompletedResult(s,u,[],a):{status:"pending",response:{timestamp:a,modelId:this.modelId,headers:u}}}},ev=r.z.object({name:r.z.string().nullish(),done:r.z.boolean().nullish(),error:r.z.object({code:r.z.number().nullish(),message:r.z.string(),status:r.z.string().nullish()}).nullish(),response:r.z.object({generateVideoResponse:r.z.object({generatedSamples:r.z.array(r.z.object({video:r.z.object({uri:r.z.string().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}),e_=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({candidates:r.z.array(r.z.object({content:r.z.object({parts:r.z.array(r.z.object({inlineData:r.z.object({mimeType:r.z.string().nullish(),data:r.z.string().nullish()}).nullish()})).nullish()}).nullish()})).nullish()}))),eb=r.z.object({voiceName:r.z.string()}),ez=r.z.object({prebuiltVoiceConfig:eb}),ew=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({multiSpeakerVoiceConfig:r.z.object({speakerVoiceConfigs:r.z.array(r.z.object({speaker:r.z.string(),voiceConfig:ez}))}).optional()}))),ex="Kore",eS=class e{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v4"}static[n.WORKFLOW_SERIALIZE](e){return(0,t.serializeModelOptions)({modelId:e.modelId,config:e.config})}static[n.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async getArgs({text:e,voice:o=ex,outputFormat:n,instructions:r,speed:a,language:i,providerOptions:l}){let s,u=[],c=this.config.provider.includes("vertex")?["googleVertex","vertex"]:["google"];for(let e of c)if(null!=(s=await (0,t.parseProviderOptions)({provider:e,providerOptions:l,schema:ew})))break;null!=s||c.includes("google")||(s=await (0,t.parseProviderOptions)({provider:"google",providerOptions:l,schema:ew}));let d=null==s?void 0:s.multiSpeakerVoiceConfig,p=e;null!=r&&(d?u.push({type:"unsupported",feature:"instructions",details:"Google Gemini TTS ignores `instructions` when `multiSpeakerVoiceConfig` is set, because prepending them would break multi-speaker transcript parsing."}):p=`${r}: ${e}`),null!=a&&u.push({type:"unsupported",feature:"speed",details:"Google Gemini TTS models do not support the `speed` option. It was ignored."}),null!=i&&u.push({type:"unsupported",feature:"language",details:"Google Gemini TTS models do not support the `language` option. Language is detected automatically from the input text."});let m="wav";return"pcm"===n?m="pcm":null!=n&&"wav"!==n&&u.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${n}. Using wav instead.`}),{requestBody:{contents:[{role:"user",parts:[{text:p}]}],generationConfig:{responseModalities:["AUDIO"],speechConfig:d?{multiSpeakerVoiceConfig:d}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:o}}}}},warnings:u,outputFormat:m}}async doGenerate(e){var o,n,r,a,l,s,u,c,d,p,m;let h,g,f,y,v,_,b=null!=(r=null==(n=null==(o=this.config._internal)?void 0:o.currentDate)?void 0:n.call(o))?r:new Date,{requestBody:z,warnings:w,outputFormat:x}=await this.getArgs(e),{value:S,responseHeaders:k,rawValue:I}=await (0,t.postJsonToApi)({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:(0,t.combineHeaders)(this.config.headers?await (0,t.resolve)(this.config.headers):void 0,e.headers),body:z,failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(e_),abortSignal:e.abortSignal,fetch:this.config.fetch});for(let e of null!=(a=S.candidates)?a:[]){for(let t of null!=(s=null==(l=e.content)?void 0:l.parts)?s:[])if(null==(u=t.inlineData)?void 0:u.data){v=t.inlineData.data,_=null!=(c=t.inlineData.mimeType)?c:void 0;break}if(null!=v)break}let T=null!=(d=function(e){if(null==e)return;let t=/rate=(\d+)/.exec(e);return t?Number.parseInt(t[1],10):void 0}(_))?d:24e3,C=null!=v?(0,t.convertBase64ToUint8Array)(v):new Uint8Array(0),E="pcm"===x||0===C.length?C:(p=C,m=T,ek(f=new DataView(g=new ArrayBuffer(44+(h=p.length))),0,"RIFF"),f.setUint32(4,36+h,!0),ek(f,8,"WAVE"),ek(f,12,"fmt "),f.setUint32(16,16,!0),f.setUint16(20,1,!0),f.setUint16(22,1,!0),f.setUint32(24,m,!0),f.setUint32(28,2*m,!0),f.setUint16(32,2,!0),f.setUint16(34,16,!0),ek(f,36,"data"),f.setUint32(40,h,!0),(y=new Uint8Array(g)).set(p,44),y);return"pcm"===x&&C.length>0&&w.push({type:"unsupported",feature:"outputFormat",details:`Returning raw PCM audio (signed 16-bit little-endian, mono, ${T} Hz). These bytes have no container header and are not directly playable; see providerMetadata.google for the sample rate and mime type.`}),{audio:E,warnings:w,request:{body:JSON.stringify(z)},response:{timestamp:b,modelId:this.modelId,headers:k,body:I},providerMetadata:{google:{sampleRate:T,mimeType:null!=_?_:null}}}}};function ek(e,t,o){for(let n=0;n<o.length;n++)e.setUint8(t+n,o.charCodeAt(n))}function eI(e){var o,n,r,a,i,l,s,u;if(null==e)return(0,t.createNullLanguageModelUsage)();let c=null!=(o=e.total_input_tokens)?o:0,d=null!=(n=e.total_output_tokens)?n:0,p=null!=(r=e.total_thought_tokens)?r:0,m=null!=(a=e.total_cached_tokens)?a:0;return{inputTokens:{total:null!=(i=e.total_input_tokens)?i:void 0,noCache:null==e.total_input_tokens?void 0:c-m,cacheRead:null!=(l=e.total_cached_tokens)?l:void 0,cacheWrite:void 0},outputTokens:{total:null==e.total_output_tokens&&null==e.total_thought_tokens?void 0:d+p,text:null!=(s=e.total_output_tokens)?s:void 0,reasoning:null!=(u=e.total_thought_tokens)?u:void 0},raw:e}}function eT(e){let t=null==e?void 0:e.output_tokens_by_modality;if(null==t)return;let o={};for(let e of t)(null==e?void 0:e.modality)!=null&&null!=e.tokens&&(o[e.modality]=e.tokens);return Object.keys(o).length>0?o:void 0}var eC={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function eE(e){let t=e.toLowerCase();for(let[e,o]of Object.entries(eC))if(t.endsWith(`.${e}`))return o;return"application/octet-stream"}function eM(e){let t=e.split("/"),o=t[t.length-1];return o&&o.length>0?o:void 0}function ej({block:e,generateId:t}){var o,n,r,a,i,l,s,u,c,d,p;let m=[];switch(e.type){case"url_context_result":for(let n of null!=(o=e.result)?o:[])(null==n?void 0:n.url)!=null&&0!==n.url.length&&(null==n.status||"success"===n.status)&&m.push({type:"source",sourceType:"url",id:t(),url:n.url});break;case"google_search_result":for(let o of null!=(n=e.result)?n:[]){let e=null==o?void 0:o.url;null!=e&&0!==e.length&&m.push({type:"source",sourceType:"url",id:t(),url:e,...null!=o.title?{title:o.title}:{}})}break;case"google_maps_result":for(let o of null!=(r=e.result)?r:[])for(let e of null!=(a=o.places)?a:[])null!=e.url&&0!==e.url.length&&m.push({type:"source",sourceType:"url",id:t(),url:e.url,...null!=e.name?{title:e.name}:{}});break;case"file_search_result":for(let o of null!=(i=e.result)?i:[]){if(null==o||"object"!=typeof o)continue;let e=null!=(s=null!=(l=o.url)?l:o.document_uri)?s:o.file_name;if(null==e||0===e.length)continue;if(e.startsWith("http://")||e.startsWith("https://")){m.push({type:"source",sourceType:"url",id:t(),url:e,...null!=o.title?{title:o.title}:{}});continue}let n=null!=(u=o.file_name)?u:eM(e),r=eE(e);m.push({type:"source",sourceType:"document",id:t(),mediaType:r,title:null!=(p=null!=(d=null!=(c=o.title)?c:o.file_name)?d:n)?p:e,...null!=n?{filename:n}:{}})}}return m}function eA({annotations:e,generateId:t}){var o;if(null==e)return[];let n=new Set,r=[];for(let a of e){let e=function({annotation:e,generateId:t}){var o,n,r,a,i;switch(e.type){case"url_citation":if(null==e.url||0===e.url.length)return;return{type:"source",sourceType:"url",id:t(),url:e.url,...null!=e.title?{title:e.title}:{}};case"file_citation":{let l=null!=(n=null!=(o=e.url)?o:e.document_uri)?n:e.file_name;if(null==l||0===l.length)return;if(l.startsWith("http://")||l.startsWith("https://"))return{type:"source",sourceType:"url",id:t(),url:l,...null!=e.file_name?{title:e.file_name}:{}};let s=null!=(r=e.file_name)?r:eM(l),u=eE(l);return{type:"source",sourceType:"document",id:t(),mediaType:u,title:null!=(i=null!=(a=e.file_name)?a:s)?i:l,...null!=s?{filename:s}:{}}}case"place_citation":if(null==e.url||0===e.url.length)return;return{type:"source",sourceType:"url",id:t(),url:e.url,...null!=e.name?{title:e.name}:{}};default:return}}({annotation:a,generateId:t});if(null==e)continue;let i="url"===e.sourceType?`url:${e.url}`:`doc:${null!=(o=e.filename)?o:e.title}`;n.has(i)||(n.add(i),r.push(e))}return r}function eO({status:e,hasFunctionCall:t}){switch(e){case"completed":return t?"tool-calls":"stop";case"requires_action":return"tool-calls";case"failed":return"error";case"incomplete":return"length";default:return"other"}}var eR=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),eN=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function eP({warnings:e,generateId:o,includeRawChunks:n,serviceTier:r}){let a,i,l,s=r,u=!1,c=new Map,d=new Set;function p(e){var t;return"url"===e.sourceType?`url:${e.url}`:`doc:${null!=(t=e.filename)?t:e.title}`}return new TransformStream({start(t){t.enqueue({type:"stream-start",warnings:e})},transform(e,r){var m,h,g,f,y,v,_,b,z,w,x,S,k,I,T,C,E,M,j,A;if(n&&r.enqueue({type:"raw",rawValue:e.rawValue}),!e.success){l="failed",r.enqueue({type:"error",error:e.error});return}let O=e.value,R=O.event_type;switch(R){case"interaction.created":{let e,t=O.interaction;a=(null==t?void 0:t.id)!=null&&t.id.length>0?t.id:void 0;let o=null==t?void 0:t.created;if("string"==typeof o){let t=new Date(o);Number.isNaN(t.getTime())||(e=t)}r.enqueue({type:"response-metadata",...null!=a?{id:a}:{},modelId:null==t?void 0:t.model,...e?{timestamp:e}:{}});break}case"step.start":{let e=O.step,t=O.index,n=`${null!=a?a:"interaction"}:${t}`,i=null==e?void 0:e.type;if("model_output"===i){let a=null==(m=null==e?void 0:e.content)?void 0:m[0];if((null==a?void 0:a.type)==="text")for(let e of(c.set(t,{kind:"text",id:n,emittedSourceKeys:new Set}),r.enqueue({type:"text-start",id:n}),eA({annotations:a.annotations,generateId:o}))){let t=p(e);d.has(t)||(d.add(t),r.enqueue(e))}else(null==a?void 0:a.type)==="image"?c.set(t,{kind:"image",id:n,...null!=a.data?{data:a.data}:{},...null!=a.mime_type?{mimeType:a.mime_type}:{},...null!=a.uri?{uri:a.uri}:{}}):c.set(t,{kind:"pending_model_output",id:n})}else if("thought"===i){let o=null==e?void 0:e.signature;if(c.set(t,{kind:"reasoning",id:n,...null!=o?{signature:o}:{}}),r.enqueue({type:"reasoning-start",id:n}),Array.isArray(null==e?void 0:e.summary))for(let t of e.summary)(null==t?void 0:t.type)==="text"&&"string"==typeof t.text&&r.enqueue({type:"reasoning-delta",id:n,delta:t.text})}else if("processing_call"===i||"processing_result"===i){let o={};(null==e?void 0:e.signature)!=null&&(o.signature=e.signature),null!=a&&(o.interactionId=a),"processing_call"===i?o.processingId=(null==e?void 0:e.id)||n:o.processingCallId=(null==e?void 0:e.call_id)||n,c.set(t,{kind:"custom",id:n,customKind:`google.${i}`,google:o})}else if("function_call"===i){let o=(null==e?void 0:e.id)||n,a=null!=(h=null==e?void 0:e.name)?h:"unknown";u=!0;let i={kind:"function_call",id:n,toolCallId:o,toolName:a,argumentsAccum:"",...(null==e?void 0:e.signature)!=null?{signature:e.signature}:{}};c.set(t,i),r.enqueue({type:"tool-input-start",id:o,toolName:a})}else if(null!=i&&eR.has(i)){let o="mcp_server_tool_call"===i?null!=(g=null==e?void 0:e.name)?g:"mcp_server_tool":i.replace(/_call$/,""),r=(null==e?void 0:e.id)||n,a={kind:"builtin_tool_call",id:n,blockType:i,toolCallId:r,toolName:o,arguments:null!=(f=null==e?void 0:e.arguments)?f:{},callEmitted:!1};c.set(t,a)}else if(null!=i&&eN.has(i)){let o="mcp_server_tool_result"===i?null!=(y=null==e?void 0:e.name)?y:"mcp_server_tool":i.replace(/_result$/,""),r=(null==e?void 0:e.call_id)||n,a={kind:"builtin_tool_result",id:n,blockType:i,callId:r,toolName:o,result:null!=(v=null==e?void 0:e.result)?v:null,...(null==e?void 0:e.is_error)!=null?{isError:e.is_error}:{},resultEmitted:!1};c.set(t,a)}else c.set(t,{kind:"unknown",id:n});break}case"step.delta":{let e=c.get(O.index);if(null==e)break;let t=null==(_=O.delta)?void 0:_.type;if("pending_model_output"===e.kind&&("text"===t||"text_annotation"===t||"text_annotation_delta"===t)){let t={kind:"text",id:e.id,emittedSourceKeys:new Set};c.set(O.index,t),e=t,r.enqueue({type:"text-start",id:t.id})}if("image"===t&&("pending_model_output"===e.kind||"text"===e.kind||"image"===e.kind)){let t=O.delta,o={};null!=a&&(o.interactionId=a);let n=Object.keys(o).length>0?{google:o}:void 0;(null==t?void 0:t.data)!=null&&t.data.length>0?r.enqueue({type:"file",mediaType:null!=(b=t.mime_type)?b:"image/png",data:{type:"data",data:t.data},...n?{providerMetadata:n}:{}}):(null==t?void 0:t.uri)!=null&&t.uri.length>0&&r.enqueue({type:"file",mediaType:null!=(z=t.mime_type)?z:"image/png",data:{type:"url",url:new URL(t.uri)},...n?{providerMetadata:n}:{}}),"image"===e.kind&&(e.data=void 0,e.uri=void 0);break}if("video"===t&&("pending_model_output"===e.kind||"text"===e.kind)){let e=O.delta,t={};null!=a&&(t.interactionId=a);let o=Object.keys(t).length>0?{google:t}:void 0;(null==e?void 0:e.data)!=null&&e.data.length>0?r.enqueue({type:"file",mediaType:null!=(w=e.mime_type)?w:"video/mp4",data:{type:"data",data:e.data},...o?{providerMetadata:o}:{}}):(null==e?void 0:e.uri)!=null&&e.uri.length>0&&r.enqueue({type:"file",mediaType:null!=(x=e.mime_type)?x:"video/mp4",data:{type:"url",url:new URL(e.uri)},...o?{providerMetadata:o}:{}});break}let n=O.delta;if("custom"===e.kind&&((null==n?void 0:n.type)==="processing_call"||(null==n?void 0:n.type)==="processing_result"))null!=n.signature&&(e.google.signature=n.signature),"processing_call"===n.type&&null!=n.id&&n.id.length>0&&(e.google.processingId=n.id),"processing_result"===n.type&&null!=n.call_id&&n.call_id.length>0&&(e.google.processingCallId=n.call_id);else if("text"===e.kind&&(null==n?void 0:n.type)==="text"){let t=null!=(S=n.text)?S:"";t.length>0&&r.enqueue({type:"text-delta",id:e.id,delta:t})}else if("text"===e.kind&&((null==n?void 0:n.type)==="text_annotation"||(null==n?void 0:n.type)==="text_annotation_delta"))for(let t of eA({annotations:n.annotations,generateId:o})){let o=p(t);d.has(o)||(d.add(o),e.emittedSourceKeys.add(o),r.enqueue(t))}else if("image"===e.kind&&(null==n?void 0:n.type)==="image")null!=n.data&&(e.data=n.data),null!=n.mime_type&&(e.mimeType=n.mime_type),null!=n.uri&&(e.uri=n.uri);else if("reasoning"===e.kind){if((null==n?void 0:n.type)==="thought_summary"){let t=n.content;(null==t?void 0:t.type)==="text"&&"string"==typeof t.text&&r.enqueue({type:"reasoning-delta",id:e.id,delta:t.text})}else if((null==n?void 0:n.type)==="thought_signature"){let t=n.signature;null!=t&&(e.signature=t)}}else if("function_call"===e.kind&&(null==n?void 0:n.type)==="arguments_delta"){let t="string"==typeof n.arguments?n.arguments:"";t.length>0&&(e.argumentsAccum+=t,r.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:t})),null!=n.id&&n.id.length>0&&(e.toolCallId=n.id),null!=n.signature&&(e.signature=n.signature),u=!0}else"builtin_tool_call"===e.kind&&(null==n?void 0:n.type)===e.blockType?(null!=n.id&&n.id.length>0&&(e.toolCallId=n.id),null!=n.arguments&&"object"==typeof n.arguments&&(e.arguments=n.arguments),null!=n.name&&"mcp_server_tool_call"===e.blockType&&(e.toolName=n.name)):"builtin_tool_result"===e.kind&&(null==n?void 0:n.type)===e.blockType&&(null!=n.call_id&&n.call_id.length>0&&(e.callId=n.call_id),void 0!==n.result&&(e.result=n.result),null!=n.is_error&&(e.isError=n.is_error),null!=n.name&&"mcp_server_tool_result"===e.blockType&&(e.toolName=n.name));break}case"step.stop":{let e=c.get(O.index);if(null==e)break;if("text"===e.kind){let t=null!=a?{google:{interactionId:a}}:void 0;r.enqueue({type:"text-end",id:e.id,...t?{providerMetadata:t}:{}})}else if("reasoning"===e.kind){let t={};null!=e.signature&&(t.signature=e.signature),null!=a&&(t.interactionId=a);let o=Object.keys(t).length>0?{google:t}:void 0;r.enqueue({type:"reasoning-end",id:e.id,...o?{providerMetadata:o}:{}})}else if("image"===e.kind){let t={};null!=a&&(t.interactionId=a);let o=Object.keys(t).length>0?{google:t}:void 0;null!=e.data&&e.data.length>0?r.enqueue({type:"file",mediaType:null!=(k=e.mimeType)?k:"image/png",data:{type:"data",data:e.data},...o?{providerMetadata:o}:{}}):null!=e.uri&&e.uri.length>0&&r.enqueue({type:"file",mediaType:null!=(I=e.mimeType)?I:"image/png",data:{type:"url",url:new URL(e.uri)},...o?{providerMetadata:o}:{}})}else if("function_call"===e.kind){let t=e.argumentsAccum.length>0?e.argumentsAccum:"{}";r.enqueue({type:"tool-input-end",id:e.toolCallId});let o={};null!=e.signature&&(o.signature=e.signature),null!=a&&(o.interactionId=a);let n=Object.keys(o).length>0?{google:o}:void 0;r.enqueue({type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t,...n?{providerMetadata:n}:{}})}else if("custom"===e.kind)r.enqueue({type:"custom",kind:e.customKind,providerMetadata:{google:e.google}});else if("builtin_tool_call"!==e.kind||e.callEmitted){if("builtin_tool_result"===e.kind&&!e.resultEmitted)for(let t of(r.enqueue({type:"tool-result",toolCallId:e.callId,toolName:e.toolName,result:null!=(C=e.result)?C:null}),e.resultEmitted=!0,ej({block:{type:e.blockType,call_id:e.callId,result:e.result},generateId:o}))){let e=p(t);d.has(e)||(d.add(e),r.enqueue(t))}}else r.enqueue({type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:JSON.stringify(null!=(T=e.arguments)?T:{}),providerExecuted:!0}),e.callEmitted=!0;c.delete(O.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":l=null!=O.status?O.status:"interaction.requires_action"===R?"requires_action":"in_progress";break;case"interaction.completed":{let e=O.interaction;(null==e?void 0:e.id)!=null&&e.id.length>0&&(a=e.id),(null==e?void 0:e.status)!=null&&(l=e.status),(null==e?void 0:e.usage)!=null&&(i=e.usage),(null==e?void 0:e.service_tier)!=null&&(s=e.service_tier);break}case"error":l="failed",r.enqueue({type:"error",error:(0,t.createProviderStreamError)({message:null!=(M=null==(E=O.error)?void 0:E.message)?M:"Unknown interaction error",type:O.event_type,code:null!=(A=null==(j=O.error)?void 0:j.code)?A:void 0,data:O})})}},flush(e){let t={unified:eO({status:l,hasFunctionCall:u}),raw:l},o=eT(i),n={google:{...null!=a?{interactionId:a}:{},...null!=s?{serviceTier:s}:{},...null!=o?{outputTokensByModality:o}:{}}};e.enqueue({type:"finish",finishReason:t,usage:eI(i),providerMetadata:n})}})}function e$({part:e,warnings:o,mediaResolution:n}){let r;if("text"===e.data.type)return{type:"text",text:e.data.text};switch((0,t.getTopLevelMediaType)(e.mediaType)){case"image":r="image";break;case"audio":r="audio";break;case"video":r="video";break;case"application":case"text":r="document";break;default:r=void 0}if(null==r)return void o.push({type:"other",message:`google.interactions: unsupported file media type "${e.mediaType}"; part dropped.`});let a=null!=n&&("image"===r||"video"===r)?{resolution:n}:{},i="video"===r?function({part:e,warnings:t}){var o,n;let r=null==(n=null==(o=e.providerOptions)?void 0:o.google)?void 0:n.processing;return null==r?{}:"agentic"===r||"static"===r?{processing:r}:"object"!=typeof r||Array.isArray(r)||"static"!==r.type?(t.push({type:"other",message:'google.interactions: invalid providerOptions.google.processing on video file part; expected "agentic", "static", or a static processing configuration. Option dropped.'}),{}):{processing:{type:"static",..."number"==typeof r.startOffset?{start_offset:r.startOffset}:{},..."number"==typeof r.endOffset?{end_offset:r.endOffset}:{},..."number"==typeof r.fps?{fps:r.fps}:{}}}}({part:e,warnings:o}):{};switch(e.data.type){case"data":{let o=(0,t.resolveFullMediaType)({part:e});return{type:r,data:(0,t.convertToBase64)(e.data.data),mime_type:o,...a,...i}}case"url":return{type:r,uri:e.data.url.toString(),...(0,t.isFullMediaType)(e.mediaType)?{mime_type:e.mediaType}:{},...a,...i};case"reference":return{type:r,uri:(0,t.resolveProviderReference)({reference:e.data.reference,provider:"google"}),...(0,t.isFullMediaType)(e.mediaType)?{mime_type:e.mediaType}:{},...a,...i}}}var eq=()=>r.z.object({modality:r.z.string().nullish(),tokens:r.z.number().nullish()}).loose(),eL=()=>r.z.object({total_input_tokens:r.z.number().nullish(),total_output_tokens:r.z.number().nullish(),total_thought_tokens:r.z.number().nullish(),total_cached_tokens:r.z.number().nullish(),total_tool_use_tokens:r.z.number().nullish(),total_tokens:r.z.number().nullish(),input_tokens_by_modality:r.z.array(eq()).nullish(),output_tokens_by_modality:r.z.array(eq()).nullish(),cached_tokens_by_modality:r.z.array(eq()).nullish(),tool_use_tokens_by_modality:r.z.array(eq()).nullish(),grounding_tool_count:r.z.array(r.z.object({type:r.z.string().nullish(),count:r.z.number().nullish()}).loose()).nullish()}).loose(),eD=()=>r.z.enum(["in_progress","requires_action","completed","failed","cancelled","incomplete"]),eU=()=>{let e=r.z.object({type:r.z.literal("url_citation"),url:r.z.string().nullish(),title:r.z.string().nullish(),start_index:r.z.number().nullish(),end_index:r.z.number().nullish()}).loose(),t=r.z.object({type:r.z.literal("file_citation"),file_name:r.z.string().nullish(),document_uri:r.z.string().nullish(),url:r.z.string().nullish(),page_number:r.z.number().nullish(),media_id:r.z.string().nullish(),start_index:r.z.number().nullish(),end_index:r.z.number().nullish(),custom_metadata:r.z.record(r.z.string(),r.z.unknown()).nullish()}).loose(),o=r.z.object({type:r.z.literal("place_citation"),name:r.z.string().nullish(),url:r.z.string().nullish(),place_id:r.z.string().nullish(),start_index:r.z.number().nullish(),end_index:r.z.number().nullish()}).loose();return r.z.union([e,t,o,r.z.object({type:r.z.string()}).loose()])},eF=()=>r.z.object({type:r.z.string(),text:r.z.string().nullish(),data:r.z.string().nullish(),mime_type:r.z.string().nullish()}).loose(),eH=()=>{let e=r.z.object({type:r.z.literal("text"),text:r.z.string(),annotations:r.z.array(eU()).nullish()}).loose(),t=r.z.object({type:r.z.literal("image"),data:r.z.string().nullish(),mime_type:r.z.string().nullish(),resolution:r.z.enum(["low","medium","high","ultra_high"]).nullish(),uri:r.z.string().nullish()}).loose(),o=r.z.object({type:r.z.literal("video"),data:r.z.string().nullish(),mime_type:r.z.string().nullish(),uri:r.z.string().nullish()}).loose();return r.z.union([e,t,o,r.z.object({type:r.z.string()}).loose()])},eB=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],eV=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],eJ=()=>{let e=r.z.object({type:r.z.literal("user_input"),content:r.z.array(eH()).nullish()}).loose(),t=r.z.object({type:r.z.literal("model_output"),content:r.z.array(eH()).nullish()}).loose(),o=r.z.object({type:r.z.literal("function_call"),id:r.z.string(),name:r.z.string(),arguments:r.z.record(r.z.string(),r.z.unknown()).nullish(),signature:r.z.string().nullish()}).loose(),n=r.z.object({type:r.z.literal("thought"),signature:r.z.string().nullish(),summary:r.z.array(eF()).nullish()}).loose(),a=r.z.object({type:r.z.literal("processing_call"),id:r.z.string(),signature:r.z.string().nullish()}).loose(),i=r.z.object({type:r.z.literal("processing_result"),call_id:r.z.string(),signature:r.z.string().nullish()}).loose(),l=r.z.object({type:r.z.enum(eB),id:r.z.string(),arguments:r.z.record(r.z.string(),r.z.unknown()).nullish(),name:r.z.string().nullish(),server_name:r.z.string().nullish(),search_type:r.z.string().nullish(),signature:r.z.string().nullish()}).loose(),s=r.z.object({type:r.z.enum(eV),call_id:r.z.string(),result:r.z.unknown().nullish(),is_error:r.z.boolean().nullish(),name:r.z.string().nullish(),server_name:r.z.string().nullish(),signature:r.z.string().nullish()}).loose();return r.z.union([e,t,o,n,a,i,l,s,r.z.object({type:r.z.string()}).loose()])},eW=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({id:r.z.string().nullish(),created:r.z.string().nullish(),updated:r.z.string().nullish(),status:eD(),model:r.z.string().nullish(),agent:r.z.string().nullish(),steps:r.z.array(eJ()).nullish(),usage:eL().nullish(),service_tier:r.z.string().nullish(),previous_interaction_id:r.z.string().nullish(),response_modalities:r.z.array(r.z.string()).nullish()}).loose())),eK=(0,t.lazySchema)(()=>{let e,o,n,a,i,l,s,u,c,d,p,m,h,g,f,y,v,_,b,z,w,x,S,k;return(0,t.zodSchema)((e=eD(),o=eU(),n=eF(),a=r.z.object({event_type:r.z.literal("interaction.created"),event_id:r.z.string().nullish(),interaction:r.z.object({id:r.z.string().nullish(),created:r.z.string().nullish(),model:r.z.string().nullish(),agent:r.z.string().nullish(),status:e.nullish()}).loose()}).loose(),i=r.z.object({event_type:r.z.literal("step.start"),event_id:r.z.string().nullish(),index:r.z.number(),step:eJ()}).loose(),l=r.z.object({type:r.z.literal("text"),text:r.z.string()}).loose(),s=r.z.object({type:r.z.literal("thought_summary"),content:n.nullish()}).loose(),u=r.z.object({type:r.z.literal("thought_signature"),signature:r.z.string().nullish()}).loose(),c=r.z.object({type:r.z.literal("arguments_delta"),arguments:r.z.string().nullish(),id:r.z.string().nullish(),signature:r.z.string().nullish()}).loose(),d=r.z.object({type:r.z.enum(["text_annotation_delta","text_annotation"]),annotations:r.z.array(o).nullish()}).loose(),p=r.z.object({type:r.z.literal("image"),data:r.z.string().nullish(),mime_type:r.z.string().nullish(),resolution:r.z.enum(["low","medium","high","ultra_high"]).nullish(),uri:r.z.string().nullish()}).loose(),m=r.z.object({type:r.z.literal("video"),data:r.z.string().nullish(),mime_type:r.z.string().nullish(),uri:r.z.string().nullish()}).loose(),h=r.z.object({type:r.z.enum(eB),id:r.z.string().nullish(),arguments:r.z.record(r.z.string(),r.z.unknown()).nullish(),name:r.z.string().nullish(),server_name:r.z.string().nullish(),search_type:r.z.string().nullish(),signature:r.z.string().nullish()}).loose(),g=r.z.object({type:r.z.enum(eV),call_id:r.z.string().nullish(),result:r.z.unknown().nullish(),is_error:r.z.boolean().nullish(),name:r.z.string().nullish(),server_name:r.z.string().nullish(),signature:r.z.string().nullish()}).loose(),f=r.z.object({type:r.z.string()}).loose(),y=r.z.union([l,p,m,s,u,c,d,h,g,f]),v=r.z.object({event_type:r.z.literal("step.delta"),event_id:r.z.string().nullish(),index:r.z.number(),delta:y}).loose(),_=r.z.object({event_type:r.z.literal("step.stop"),event_id:r.z.string().nullish(),index:r.z.number()}).loose(),b=r.z.object({event_type:r.z.literal("interaction.status_update"),event_id:r.z.string().nullish(),interaction_id:r.z.string().nullish(),status:e.nullish()}).loose(),z=r.z.object({event_type:r.z.literal("interaction.in_progress"),event_id:r.z.string().nullish(),interaction_id:r.z.string().nullish(),status:e.nullish()}).loose(),w=r.z.object({event_type:r.z.literal("interaction.requires_action"),event_id:r.z.string().nullish(),interaction_id:r.z.string().nullish(),status:e.nullish()}).loose(),x=r.z.object({event_type:r.z.literal("interaction.completed"),event_id:r.z.string().nullish(),interaction:r.z.object({id:r.z.string().nullish(),status:e.nullish(),usage:eL().nullish(),service_tier:r.z.string().nullish()}).loose()}).loose(),S=r.z.object({event_type:r.z.literal("error"),event_id:r.z.string().nullish(),error:r.z.object({code:r.z.string().nullish(),message:r.z.string().nullish()}).loose().nullish()}).loose(),k=r.z.object({event_type:r.z.string()}).loose(),r.z.union([a,i,v,_,b,z,w,x,S,k])))}),eG=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({previousInteractionId:r.z.string().nullish(),store:r.z.boolean().nullish(),agent:r.z.string().nullish(),agentConfig:r.z.union([r.z.object({type:r.z.literal("dynamic")}).loose(),r.z.object({type:r.z.literal("deep-research"),thinkingSummaries:r.z.enum(["auto","none"]).nullish(),visualization:r.z.enum(["off","auto"]).nullish(),collaborativePlanning:r.z.boolean().nullish()})]).nullish(),thinkingLevel:r.z.enum(["minimal","low","medium","high"]).nullish(),thinkingSummaries:r.z.enum(["auto","none"]).nullish(),responseFormat:r.z.array(r.z.union([r.z.object({type:r.z.literal("text"),mimeType:r.z.string().nullish(),schema:r.z.unknown().nullish()}).loose(),r.z.object({type:r.z.literal("image"),mimeType:r.z.string().nullish(),aspectRatio:r.z.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:r.z.enum(["1K","2K","4K","512"]).nullish()}).loose(),r.z.object({type:r.z.literal("audio"),mimeType:r.z.string().nullish()}).loose(),r.z.object({type:r.z.literal("video"),aspectRatio:r.z.enum(["16:9","9:16"]).nullish(),resolution:r.z.enum(["360p","720p","1080p","4k"]).nullish(),duration:r.z.string().nullish(),delivery:r.z.enum(["inline","uri"]).nullish(),gcsUri:r.z.string().nullish()}).loose()])).nullish(),imageConfig:r.z.object({aspectRatio:r.z.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:r.z.enum(["1K","2K","4K","512"]).nullish()}).nullish(),mediaResolution:r.z.enum(["low","medium","high","ultra_high"]).nullish(),responseModalities:r.z.array(r.z.enum(["text","image","audio","video","document"])).nullish(),serviceTier:r.z.enum(["flex","standard","priority"]).nullish(),systemInstruction:r.z.string().nullish(),signature:r.z.string().nullish(),interactionId:r.z.string().nullish(),pollingTimeoutMs:r.z.number().int().positive().nullish(),background:r.z.boolean().nullish(),environment:r.z.union([r.z.string(),r.z.object({type:r.z.literal("remote"),sources:r.z.array(r.z.union([r.z.object({type:r.z.literal("gcs"),source:r.z.string(),target:r.z.string().nullish()}),r.z.object({type:r.z.literal("repository"),source:r.z.string(),target:r.z.string().nullish()}),r.z.object({type:r.z.literal("inline"),content:r.z.string(),target:r.z.string()})])).nullish(),network:r.z.union([r.z.literal("disabled"),r.z.object({allowlist:r.z.array(r.z.object({domain:r.z.string(),transform:r.z.array(r.z.record(r.z.string(),r.z.string())).nullish()}))})]).nullish()})]).nullish()})));function eY({signature:e,interactionId:t,processingId:o,processingCallId:n}){let r={};return null!=e&&(r.signature=e),null!=t&&(r.interactionId=t),null!=o&&(r.processingId=o),null!=n&&(r.processingCallId=n),Object.keys(r).length>0?{providerMetadata:{google:r}}:{}}var eX=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),eZ=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function eQ({steps:e,generateId:t,interactionId:o}){var n,r,a,i,l,s,u,c,d,p,m;let h=[],g=!1;if(null==e)return{content:h,hasFunctionCall:g};for(let f of e){if(null==f||"object"!=typeof f)continue;let e=f.type;if("string"==typeof e)switch(e){case"user_input":break;case"model_output":for(let e of null!=(n=f.content)?n:[]){if(null==e||"object"!=typeof e)continue;let n=e.type;if("text"===n){let n=null!=(r=e.text)?r:"",a=e.annotations;for(let e of(h.push({type:"text",text:n,...eY({interactionId:o})}),eA({annotations:a,generateId:t})))h.push(e)}else"image"===n?null!=e.data&&e.data.length>0?h.push({type:"file",mediaType:null!=(a=e.mime_type)?a:"image/png",data:{type:"data",data:e.data},...eY({interactionId:o})}):null!=e.uri&&e.uri.length>0&&h.push({type:"file",mediaType:null!=(i=e.mime_type)?i:"image/png",data:{type:"url",url:new URL(e.uri)},...eY({interactionId:o})}):"video"===n&&(null!=e.data&&e.data.length>0?h.push({type:"file",mediaType:null!=(l=e.mime_type)?l:"video/mp4",data:{type:"data",data:e.data},...eY({interactionId:o})}):null!=e.uri&&e.uri.length>0&&h.push({type:"file",mediaType:null!=(s=e.mime_type)?s:"video/mp4",data:{type:"url",url:new URL(e.uri)},...eY({interactionId:o})}))}break;case"thought":{let e=(Array.isArray(f.summary)?f.summary:[]).filter(e=>(null==e?void 0:e.type)==="text"&&"string"==typeof e.text).map(e=>e.text).join("\n");h.push({type:"reasoning",text:e,...eY({signature:f.signature,interactionId:o})});break}case"processing_call":{let e=f.id||t();h.push({type:"custom",kind:"google.processing_call",...eY({signature:f.signature,interactionId:o,processingId:e})});break}case"processing_result":{let e=f.call_id||t();h.push({type:"custom",kind:"google.processing_result",...eY({signature:f.signature,interactionId:o,processingCallId:e})});break}case"function_call":g=!0,h.push({type:"tool-call",toolCallId:f.id,toolName:f.name,input:JSON.stringify(null!=(u=f.arguments)?u:{}),...eY({signature:f.signature,interactionId:o})});break;default:if(eX.has(e)){let o="mcp_server_tool_call"===e?null!=(c=f.name)?c:"mcp_server_tool":e.replace(/_call$/,""),n=JSON.stringify(null!=(d=f.arguments)?d:{});h.push({type:"tool-call",toolCallId:f.id||t(),toolName:o,input:n,providerExecuted:!0})}else if(eZ.has(e)){let o="mcp_server_tool_result"===e?null!=(p=f.name)?p:"mcp_server_tool":e.replace(/_result$/,"");for(let e of(h.push({type:"tool-result",toolCallId:f.call_id||t(),toolName:o,result:null!=(m=f.result)?m:null}),ej({block:f,generateId:t})))h.push(e)}}}return{content:h,hasFunctionCall:g}}async function e0({baseURL:e,interactionId:o,headers:n,fetch:r=globalThis.fetch}){if(null==o||0===o.length)return;let a=`${e}/interactions/${encodeURIComponent(o)}/cancel`;try{let e=await r(a,{method:"POST",headers:(0,t.withUserAgentSuffix)((0,t.combineHeaders)({"Content-Type":"application/json"},n),(0,t.getRuntimeEnvironmentUserAgent)()),body:"{}"});try{await e.text()}catch(e){}}catch(e){}}var e1=new Set(["completed","failed","cancelled","incomplete"]);function e2(e){return null!=e&&e1.has(e)}async function e4({baseURL:e,interactionId:o,headers:n,fetch:r,abortSignal:a,initialDelayMs:l=1e3,maxDelayMs:s=1e4,timeoutMs:u=18e5}){if(null==o||0===o.length)throw Error("google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.");let c=Date.now(),d=l,p=`${e}/interactions/${encodeURIComponent(o)}`,m=()=>e0({baseURL:e,interactionId:o,headers:n,fetch:r});try{for(;;){if(null==a?void 0:a.aborted)throw await m(),new DOMException("Polling was aborted","AbortError");if(Date.now()-c>u)throw Error(`google.interactions: timed out polling interaction ${o} after ${u}ms.`);await (0,t.delay)(d,{abortSignal:a});let{value:e,rawValue:l,responseHeaders:h}=await (0,t.getFromApi)({url:p,validateUrl:!1,headers:n,failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(eW),abortSignal:a,fetch:r});if(e2(e.status))return{response:e,rawResponse:l,responseHeaders:h};d=Math.min(2*d,s)}}catch(e){throw(0,t.isAbortError)(e)&&await m(),e}}var e3=class e{constructor(e,t){this.specificationVersion="v4","string"==typeof e?(this.modelId=e,this.agent=void 0):"managedAgent"in e?(this.modelId=e.managedAgent,this.agent=e.managedAgent):(this.modelId=e.agent,this.agent=e.agent),this.config=t}static[n.WORKFLOW_SERIALIZE](e){return{...(0,t.serializeModelOptions)({modelId:e.modelId,config:e.config}),agent:e.agent}}static[n.WORKFLOW_DESERIALIZE](t){return new e(null!=t.agent?{agent:t.agent}:t.modelId,t.config)}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?this.config.supportedUrls():{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(e){var o,n,r,a,i,l,s,u,c,d,p,m,h,g,f,y,v,_,b,z,w,x,S,k,I,T,C,E,M,j,A,O;let R,N,P,$,q,L=[],D=await (0,t.parseProviderOptions)({provider:"google",providerOptions:e.providerOptions,schema:eG}),U=null!=this.agent;if(U||(null!=e.frequencyPenalty&&L.push({type:"unsupported",feature:"frequencyPenalty"}),null!=e.presencePenalty&&L.push({type:"unsupported",feature:"presencePenalty"})),null!=e.tools&&e.tools.length>0){let t=function({tools:e,toolChoice:t}){var o,n,r,a;let i,l=[],s=(null==e?void 0:e.length)?e:void 0;if(null==s)return{tools:void 0,toolChoice:void 0,toolWarnings:l};let u=[];for(let e of s){if("function"===e.type){u.push({type:"function",name:e.name,description:null!=(o=e.description)?o:"",parameters:e.inputSchema});continue}if("provider"===e.type){let t=null!=(n=e.args)?n:{};switch(e.id){case"google.google_search":{let e,o=t.searchTypes;if(null!=o&&"object"==typeof o){let t=[];null!=o.webSearch&&t.push("web_search"),null!=o.imageSearch&&t.push("image_search"),t.length>0&&(e=t)}u.push({type:"google_search",...null!=e?{search_types:e}:{}});break}case"google.code_execution":u.push({type:"code_execution"});break;case"google.url_context":u.push({type:"url_context"});break;case"google.file_search":u.push({type:"file_search",...null!=t.fileSearchStoreNames?{file_search_store_names:t.fileSearchStoreNames}:{},...null!=t.topK?{top_k:t.topK}:{},...null!=t.metadataFilter?{metadata_filter:t.metadataFilter}:{}});break;case"google.google_maps":u.push({type:"google_maps",...null!=t.latitude?{latitude:t.latitude}:{},...null!=t.longitude?{longitude:t.longitude}:{},...null!=t.enableWidget?{enable_widget:t.enableWidget}:{}});break;case"google.computer_use":u.push({type:"computer_use",environment:null!=(r=t.environment)?r:"browser",...null!=t.excludedPredefinedFunctions?{excludedPredefinedFunctions:t.excludedPredefinedFunctions}:{}});break;case"google.mcp_server":u.push({type:"mcp_server",...null!=t.name?{name:t.name}:{},...null!=t.url?{url:t.url}:{},...null!=t.headers?{headers:t.headers}:{},...null!=t.allowedTools?{allowed_tools:t.allowedTools}:{}});break;case"google.retrieval":{let e=null!=(a=t.vertexAiSearchConfig)?a:void 0;u.push({type:"retrieval",...null!=t.retrievalTypes?{retrieval_types:t.retrievalTypes}:{retrieval_types:["vertex_ai_search"]},...null!=e?{vertex_ai_search_config:e}:{}});break}default:l.push({type:"unsupported",feature:`provider-defined tool ${e.id}`,details:`provider-defined tool ${e.id} is not supported by google.interactions; tool dropped.`})}continue}l.push({type:"unsupported",feature:`tool of type ${e.type}`,details:"Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."})}let c=u.some(e=>"function"===e.type);if(null!=t&&c)switch(t.type){case"auto":i="auto";break;case"required":i="any";break;case"none":i="none";break;case"tool":i={allowed_tools:{mode:"validated",tools:[t.toolName]}}}return{tools:u.length>0?u:void 0,toolChoice:i,toolWarnings:l}}({tools:e.tools,toolChoice:e.toolChoice});R=t.tools,N=t.toolChoice,L.push(...t.toolWarnings)}let F=[];if((null==(o=e.responseFormat)?void 0:o.type)==="json")if(U)L.push({type:"other",message:"google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."});else{let t={type:"text",mime_type:"application/json",...null!=e.responseFormat.schema?{schema:e.responseFormat.schema}:{}};F.push(t)}if((null==D?void 0:D.responseFormat)!=null)for(let e of D.responseFormat)"text"===e.type?F.push(e6({type:"text",mime_type:null!=(n=e.mimeType)?n:void 0,schema:null!=(r=e.schema)?r:void 0})):"image"===e.type?F.push(e6({type:"image",mime_type:null!=(a=e.mimeType)?a:void 0,aspect_ratio:null!=(i=e.aspectRatio)?i:void 0,image_size:null!=(l=e.imageSize)?l:void 0})):"audio"===e.type?F.push(e6({type:"audio",mime_type:null!=(s=e.mimeType)?s:void 0})):"video"===e.type&&F.push(e6({type:"video",aspect_ratio:null!=(u=e.aspectRatio)?u:void 0,resolution:null!=(c=e.resolution)?c:void 0,duration:null!=(d=e.duration)?d:void 0,delivery:null!=(p=e.delivery)?p:void 0,gcs_uri:null!=(m=e.gcsUri)?m:void 0}));let{input:H,systemInstruction:B,warnings:V}=function({prompt:e,previousInteractionId:o,store:n,mediaResolution:r}){var a,i,l,s,u,c,d,p;let m=[],h=null!=o&&!1===n,g=null!=o&&!1!==n;h&&m.push({type:"other",message:"google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted."});let f=g?function({prompt:e,previousInteractionId:t}){let o=[],n=new Set;for(let r of e){if("assistant"===r.role){if(r.content.some(e=>{var o,n;return(null==(n=null==(o=e.providerOptions)?void 0:o.google)?void 0:n.interactionId)===t})){for(let e of r.content)"tool-call"===e.type&&n.add(e.toolCallId);continue}o.push(r);continue}if("tool"===r.role){let e=r.content.filter(e=>"tool-result"!==e.type||!n.has(e.toolCallId));if(0===e.length)continue;o.push({...r,content:e});continue}o.push(r)}return o}({prompt:e,previousInteractionId:o}):e,y=[],v=[];for(let e of f)switch(e.role){case"system":y.push(e.content);break;case"user":{let t=[];for(let o of e.content)if("text"===o.type)t.push({type:"text",text:o.text});else if("file"===o.type){let e=e$({part:o,warnings:m,mediaResolution:r});null!=e&&t.push(e)}let o=function(e){if(e.length<2)return e;let t=[];for(let o of e){let e=t[t.length-1];if("text"===o.type&&null!=e&&"text"===e.type&&null==e.annotations&&null==o.annotations){let n={type:"text",text:`${e.text}
|
|
23
27
|
|
|
24
28
|
${o.text}`};t[t.length-1]=n;continue}t.push(o)}return t}(t);o.length>0&&v.push({type:"user_input",content:o});break}case"assistant":{let o=[],n=()=>{o.length>0&&(v.push({type:"model_output",content:o}),o=[])};for(let d of e.content)if("text"===d.type)o.push({type:"text",text:d.text});else if("reasoning"===d.type){n();let e=null==(i=null==(a=d.providerOptions)?void 0:a.google)?void 0:i.signature;v.push({type:"thought",...null!=e?{signature:e}:{},summary:d.text.length>0?[{type:"text",text:d.text}]:void 0})}else if("file"===d.type){let e=e$({part:d,warnings:m,mediaResolution:r});null!=e&&o.push(e)}else if("custom"===d.type){n();let e=null==(l=d.providerOptions)?void 0:l.google,t="string"==typeof(null==e?void 0:e.signature)?e.signature:void 0;"google.processing_call"===d.kind&&"string"==typeof(null==e?void 0:e.processingId)?v.push({type:"processing_call",id:e.processingId,...null!=t?{signature:t}:{}}):"google.processing_result"===d.kind&&"string"==typeof(null==e?void 0:e.processingCallId)?v.push({type:"processing_result",call_id:e.processingCallId,...null!=t?{signature:t}:{}}):m.push({type:"other",message:`google.interactions: unsupported or invalid custom assistant content part "${d.kind}"; part dropped.`})}else if("tool-call"===d.type){n();let e=null==(u=null==(s=d.providerOptions)?void 0:s.google)?void 0:u.signature,o="string"==typeof d.input?function(e){try{let o=(0,t.secureJsonParse)(e);if(null!=o&&"object"==typeof o&&!Array.isArray(o))return o;return{value:o}}catch(t){return{value:e}}}(d.input):null!=(c=d.input)?c:{};v.push({type:"function_call",id:d.toolCallId,name:d.toolName,arguments:o,...null!=e?{signature:e}:{}})}else m.push({type:"other",message:`google.interactions: unsupported assistant content part type "${d.type}"; part dropped.`});n();break}case"tool":{let o=[];for(let n of e.content){if("tool-result"!==n.type){m.push({type:"other",message:`google.interactions: unsupported tool message part type "${n.type}"; part dropped.`});continue}let e=function({toolCallId:e,toolName:o,output:n,signature:r,warnings:a}){var i;let l={type:"function_result",call_id:e,name:o,...null!=r?{signature:r}:{}};switch(n.type){case"text":return{...l,result:n.value};case"json":return{...l,result:JSON.stringify(n.value)};case"error-text":return{...l,is_error:!0,result:n.value};case"error-json":return{...l,is_error:!0,result:JSON.stringify(n.value)};case"execution-denied":return{...l,is_error:!0,result:null!=(i=n.reason)?i:"Tool execution denied by user."};case"content":{let e=[];for(let o of n.value)if("text"===o.type)e.push({type:"text",text:o.text});else if("file"===o.type){if("image"!==(0,t.getTopLevelMediaType)(o.mediaType)){a.push({type:"other",message:`google.interactions: tool-result file with mediaType "${o.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let n=function({part:e,warnings:o}){switch(e.data.type){case"data":{let o=(0,t.isFullMediaType)(e.mediaType)?e.mediaType:(0,t.resolveFullMediaType)({part:{type:"file",mediaType:e.mediaType,data:e.data}});return{type:"image",data:(0,t.convertToBase64)(e.data.data),mime_type:o}}case"url":return{type:"image",uri:e.data.url.toString(),...(0,t.isFullMediaType)(e.mediaType)?{mime_type:e.mediaType}:{}};case"reference":return{type:"image",uri:(0,t.resolveProviderReference)({reference:e.data.reference,provider:"google"}),...(0,t.isFullMediaType)(e.mediaType)?{mime_type:e.mediaType}:{}};case"text":return void o.push({type:"other",message:'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'})}}({part:o,warnings:a});null!=n&&e.push(n)}else a.push({type:"other",message:`google.interactions: tool-result content part type "${o.type}" is not supported; part dropped.`});return{...l,result:e}}}}({toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,signature:null==(p=null==(d=n.providerOptions)?void 0:d.google)?void 0:p.signature,warnings:m});o.push(e)}o.length>0&&v.push({type:"user_input",content:o})}}return{input:v,systemInstruction:y.length>0?y.join("\n\n"):void 0,warnings:m}}({prompt:e.prompt,previousInteractionId:null!=(h=null==D?void 0:D.previousInteractionId)?h:void 0,store:null!=(g=null==D?void 0:D.store)?g:void 0,mediaResolution:null!=(f=null==D?void 0:D.mediaResolution)?f:void 0});L.push(...V);let J=B,W=null!=(y=null==D?void 0:D.systemInstruction)?y:void 0;if(null!=J&&null!=W?L.push({type:"other",message:"google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."}):null==J&&null!=W&&(J=W),U){let t=[];null!=e.temperature&&t.push("temperature"),null!=e.topP&&t.push("topP"),null!=e.topK&&t.push("topK"),null!=e.frequencyPenalty&&t.push("frequencyPenalty"),null!=e.presencePenalty&&t.push("presencePenalty"),null!=e.seed&&t.push("seed"),null!=e.stopSequences&&e.stopSequences.length>0&&t.push("stopSequences"),null!=e.maxOutputTokens&&t.push("maxOutputTokens"),(null==D?void 0:D.thinkingLevel)!=null&&t.push("thinkingLevel"),(null==D?void 0:D.thinkingSummaries)!=null&&t.push("thinkingSummaries"),(null==D?void 0:D.imageConfig)!=null&&t.push("imageConfig"),t.length>0&&L.push({type:"other",message:`google.interactions: ${t.join(", ")} ${1===t.length?"is":"are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`}),P=void 0}else if(P=e6({temperature:null!=(v=e.temperature)?v:void 0,top_p:null!=(_=e.topP)?_:void 0,top_k:null!=(b=e.topK)?b:void 0,seed:null!=(z=e.seed)?z:void 0,stop_sequences:null!=e.stopSequences&&e.stopSequences.length>0?e.stopSequences:void 0,max_output_tokens:null!=(w=e.maxOutputTokens)?w:void 0,thinking_level:null!=(x=null==D?void 0:D.thinkingLevel)?x:void 0,thinking_summaries:null!=(S=null==D?void 0:D.thinkingSummaries)?S:void 0,tool_choice:N}),(null==D?void 0:D.imageConfig)!=null){let e=F.some(e=>"image"===e.type);L.push({type:"other",message:e?"google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.":'google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.'}),e||F.push({type:"image",mime_type:"image/png",...null!=D.imageConfig.aspectRatio?{aspect_ratio:D.imageConfig.aspectRatio}:{},...null!=D.imageConfig.imageSize?{image_size:D.imageConfig.imageSize}:{}})}if(U&&(null==D?void 0:D.agentConfig)!=null){let e=D.agentConfig;"deep-research"===e.type?$=e6({type:"deep-research",thinking_summaries:null!=(k=e.thinkingSummaries)?k:void 0,visualization:null!=(I=e.visualization)?I:void 0,collaborative_planning:null!=(T=e.collaborativePlanning)?T:void 0}):"dynamic"===e.type&&($={type:"dynamic"})}if((null==D?void 0:D.environment)!=null)if(U)if("string"==typeof D.environment)q=D.environment;else{let e,t=D.environment,o=null==(C=t.sources)?void 0:C.map(e=>{var t;return"inline"===e.type?{type:"inline",content:e.content,target:e.target}:e6({type:e.type,source:e.source,target:null!=(t=e.target)?t:void 0})});"disabled"===t.network?e="disabled":null!=t.network&&(e={allowlist:t.network.allowlist.map(e=>{var t;return e6({domain:e.domain,transform:null!=(t=e.transform)?t:void 0})})}),q=e6({type:"remote",sources:null!=o&&o.length>0?o:void 0,network:e})}else L.push({type:"other",message:"google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."});return{args:e6({...U?{agent:this.agent}:{model:this.modelId},input:H,system_instruction:J,tools:R,response_format:F.length>0?F:void 0,response_modalities:(null==D?void 0:D.responseModalities)!=null?D.responseModalities:void 0,previous_interaction_id:null!=(E=null==D?void 0:D.previousInteractionId)?E:void 0,service_tier:null!=(M=null==D?void 0:D.serviceTier)?M:void 0,store:null!=(j=null==D?void 0:D.store)?j:void 0,generation_config:null!=P&&Object.keys(P).length>0?P:void 0,agent_config:$,environment:q,background:null!=(A=null==D?void 0:D.background)?A:void 0}),warnings:L,isAgent:U,isBackground:(null==D?void 0:D.background)===!0,pollingTimeoutMs:null!=(O=null==D?void 0:D.pollingTimeoutMs)?O:void 0}}async doGenerate(e){var o,n,r,a,l,s;let u,{args:c,warnings:d,isAgent:p,pollingTimeoutMs:m}=await this.getArgs(e),h=`${this.config.baseURL}/interactions`,g=(0,t.combineHeaders)(this.config.headers?await (0,t.resolve)(this.config.headers):void 0,e.headers),{responseHeaders:f,value:y,rawValue:v}=await (0,t.postJsonToApi)({url:h,headers:g,body:c,failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(eW),abortSignal:e.abortSignal,fetch:this.config.fetch});if(p&&!e2(y.status)){let t=await e4({baseURL:this.config.baseURL,interactionId:y.id,headers:g,fetch:this.config.fetch,abortSignal:e.abortSignal,timeoutMs:m});y=t.response,v=t.rawResponse,f=null!=(o=t.responseHeaders)?o:f}let _="string"==typeof y.id&&y.id.length>0?y.id:void 0,{content:b,hasFunctionCall:z}=eQ({steps:null!=(n=y.steps)?n:null,generateId:null!=(r=this.config.generateId)?r:t.generateId,interactionId:_}),w={unified:eO({status:y.status,hasFunctionCall:z}),raw:y.status},x=null!=(l=null!=(a=y.service_tier)?a:null==f?void 0:f["x-gemini-service-tier"])?l:void 0,S=eT(y.usage),k={google:{...null!=_?{interactionId:_}:{},...null!=x?{serviceTier:x}:{},...null!=S?{outputTokensByModality:S}:{}}};if("string"==typeof y.created){let e=new Date(y.created);Number.isNaN(e.getTime())||(u=e)}return{content:b,finishReason:w,usage:eI(y.usage),warnings:d,providerMetadata:k,request:{body:c},response:{headers:f,body:v,...null!=_?{id:_}:{},...u?{timestamp:u}:{},modelId:null!=(s=y.model)?s:void 0}}}async doStream(e){var o;let{args:n,warnings:r,isBackground:a,pollingTimeoutMs:l}=await this.getArgs(e),s=`${this.config.baseURL}/interactions`,u=(0,t.combineHeaders)(this.config.headers?await (0,t.resolve)(this.config.headers):void 0,e.headers);if(a)return this.doStreamBackground({args:n,warnings:r,url:s,mergedHeaders:u,options:e,pollingTimeoutMs:l});let c={...n,stream:!0},{responseHeaders:d,value:p}=await (0,t.postJsonToApi)({url:s,headers:u,body:c,failedResponseHandler:i,successfulResponseHandler:(0,t.createEventSourceResponseHandler)(eK),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=null==d?void 0:d["x-gemini-service-tier"],h=eP({warnings:r,generateId:null!=(o=this.config.generateId)?o:t.generateId,includeRawChunks:e.includeRawChunks,serviceTier:m});return{stream:p.pipeThrough(h),request:{body:c},response:{headers:d}}}async doStreamBackground({args:e,warnings:o,url:n,mergedHeaders:r,options:a,pollingTimeoutMs:l}){var s,u;let{responseHeaders:c,value:d}=await (0,t.postJsonToApi)({url:n,headers:r,body:e,failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(eW),abortSignal:a.abortSignal,fetch:this.config.fetch}),p=d.id;if(null==p||0===p.length)throw Error("google.interactions: background POST response did not include an interaction id; cannot stream the result.");let m=null==c?void 0:c["x-gemini-service-tier"];if(e2(d.status))return{stream:function({response:e,warnings:t,generateId:o,includeRawChunks:n,headerServiceTier:r}){return new ReadableStream({start(a){var i,l,s;let u;a.enqueue({type:"stream-start",warnings:t});let c="string"==typeof e.id&&e.id.length>0?e.id:void 0,d=e.created;if("string"==typeof d){let e=new Date(d);Number.isNaN(e.getTime())||(u=e)}a.enqueue({type:"response-metadata",...null!=c?{id:c}:{},modelId:null!=(i=e.model)?i:void 0,...u?{timestamp:u}:{}}),n&&a.enqueue({type:"raw",rawValue:e});let{content:p,hasFunctionCall:m}=eQ({steps:null!=(l=e.steps)?l:null,generateId:o,interactionId:c}),h=0,g=()=>`${null!=c?c:"agent"}:${h++}`;for(let e of p)switch(e.type){case"text":{let t=g(),o=e.providerMetadata;a.enqueue({type:"text-start",id:t}),e.text.length>0&&a.enqueue({type:"text-delta",id:t,delta:e.text}),a.enqueue({type:"text-end",id:t,...o?{providerMetadata:o}:{}});break}case"reasoning":{let t=g(),o=e.providerMetadata;a.enqueue({type:"reasoning-start",id:t}),e.text.length>0&&a.enqueue({type:"reasoning-delta",id:t,delta:e.text}),a.enqueue({type:"reasoning-end",id:t,...o?{providerMetadata:o}:{}});break}case"tool-call":{let t=e.providerMetadata;a.enqueue({type:"tool-input-start",id:e.toolCallId,toolName:e.toolName,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{}}),a.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:e.input}),a.enqueue({type:"tool-input-end",id:e.toolCallId}),a.enqueue({type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...t?{providerMetadata:t}:{}});break}case"tool-result":a.enqueue({type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,result:e.result});break;case"source":case"file":a.enqueue(e)}let f=null!=(s=e.service_tier)?s:r,y={unified:eO({status:e.status,hasFunctionCall:m}),raw:e.status},v={google:{...null!=c?{interactionId:c}:{},...null!=f?{serviceTier:f}:{}}};a.enqueue({type:"finish",finishReason:y,usage:eI(e.usage),providerMetadata:v}),a.close()}})}({response:d,warnings:o,generateId:null!=(s=this.config.generateId)?s:t.generateId,includeRawChunks:a.includeRawChunks,headerServiceTier:m}),request:{body:e},response:{headers:c}};let h=function({baseURL:e,interactionId:o,headers:n,fetch:r,abortSignal:a,maxRetries:l=3,retryDelayMs:s=500}){let u,c;if(0===o.length)throw Error("google.interactions: cannot stream a background interaction without an id.");let d={...n,accept:"text/event-stream"},p=!1,m=0,h=!1,g=new AbortController,f=()=>g.abort();null!=a&&(a.aborted?g.abort():a.addEventListener("abort",f,{once:!0}));let y=g.signal;async function v(){let n,a,{value:l}=await (0,t.getFromApi)({url:(n=`${e}/interactions/${encodeURIComponent(o)}`,a=new URLSearchParams({stream:"true"}),null!=u&&a.set("last_event_id",u),`${n}?${a.toString()}`),validateUrl:!1,headers:d,failedResponseHandler:i,successfulResponseHandler:(0,t.createEventSourceResponseHandler)(eK),abortSignal:y,fetch:r});return l.getReader()}return new ReadableStream({async start(i){try{for(;!p&&!y.aborted;){if(null==c)try{c=await v(),h=!1}catch(e){if((0,t.isAbortError)(e)||y.aborted||++m>=l)return void i.error(e);await (0,t.delay)(s*m,{abortSignal:y});continue}try{let{done:e,value:o}=await c.read();if(e){if(c=void 0,p)break;if(h)m=0;else{if(++m>=l)return void i.error(Error("google.interactions: SSE stream closed without producing any events."));await (0,t.delay)(s*m,{abortSignal:y})}continue}if(h=!0,o.success){let e=o.value;"string"==typeof e.event_id&&e.event_id.length>0&&(u=e.event_id),("interaction.completed"===e.event_type||"error"===e.event_type)&&(p=!0)}i.enqueue(o)}catch(e){if((0,t.isAbortError)(e)||y.aborted||(c=void 0,++m>=l))return void i.error(e);await (0,t.delay)(s*m,{abortSignal:y})}}i.close()}catch(e){i.error(e)}finally{null!=a&&a.removeEventListener("abort",f),null==c||c.cancel().catch(()=>{}),c=void 0,y.aborted&&!p&&await e0({baseURL:e,interactionId:o,headers:n,fetch:r})}},cancel(){g.abort(),null==c||c.cancel().catch(()=>{}),c=void 0}})}({baseURL:this.config.baseURL,interactionId:p,headers:r,fetch:this.config.fetch,abortSignal:a.abortSignal}),g=eP({warnings:o,generateId:null!=(u=this.config.generateId)?u:t.generateId,includeRawChunks:a.includeRawChunks,serviceTier:m});return{stream:h.pipeThrough(g),request:{body:e},response:{headers:c}}}};function e6(e){let t={};for(let[o,n]of Object.entries(e))void 0!==n&&(t[o]=n);return t}function e5(e){let t=new URL(e),o=t.pathname.split("/"),n=o.at(-1);return("v1beta"===n||"v1alpha"===n)&&(o.pop(),t.pathname=o.join("/")||"/"),t}function e8(e,t){let o=e5(e);return o.protocol="https:"===o.protocol?"wss:":"ws:",o.pathname=`${o.pathname.replace(/\/$/,"")}/ws/${t}`,o}var e9=class{constructor(){this.turnCounter=0,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,this.turnClosed=!1,this.inputAudioRate=16e3}get responseId(){return`google-resp-${this.turnCounter}`}get itemId(){return`google-item-${this.turnCounter}`}beginTurnIfClosed(){this.turnClosed&&(this.turnCounter++,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,this.turnClosed=!1)}parseServerEvent(e){var t,o;return null!=e.setupComplete?{type:"session-created",raw:e}:null!=e.toolCall?(this.beginTurnIfClosed(),(null!=(t=e.toolCall.functionCalls)?t:[]).flatMap(t=>{var o;let n=JSON.stringify(null!=(o=t.args)?o:{});return[{type:"function-call-arguments-delta",responseId:this.responseId,itemId:this.itemId,callId:t.id,delta:n,raw:e},{type:"function-call-arguments-done",responseId:this.responseId,itemId:this.itemId,callId:t.id,name:t.name,arguments:n,raw:e}]})):null!=e.toolCallCancellation?{type:"custom",rawType:"toolCallCancellation",raw:e}:null!=e.goAway?{type:"custom",rawType:"goAway",raw:e}:null!=e.sessionResumptionUpdate?{type:"custom",rawType:"sessionResumptionUpdate",raw:e}:null!=e.serverContent?this.parseServerContent(e.serverContent,e):(null==(o=e.inputTranscription)?void 0:o.text)!=null?{type:"input-transcription-completed",itemId:`google-input-${this.turnCounter}`,transcript:e.inputTranscription.text,raw:e}:{type:"custom",rawType:String(Object.keys(e)[0]),raw:e}}parseServerContent(e,t){var o,n,r,a;let i=[];if(e.interrupted&&i.push({type:"speech-started",raw:t}),null==(o=e.modelTurn)?void 0:o.parts)for(let o of(this.beginTurnIfClosed(),e.modelTurn.parts))(null==(n=o.inlineData)?void 0:n.data)&&(this.hasAudio=!0,i.push({type:"audio-delta",responseId:this.responseId,itemId:this.itemId,delta:o.inlineData.data,raw:t})),o.text&&(this.hasText=!0,i.push({type:"text-delta",responseId:this.responseId,itemId:this.itemId,delta:o.text,raw:t}));return((null==(r=e.outputTranscription)?void 0:r.text)&&(this.hasTranscript=!0,i.push({type:"audio-transcript-delta",responseId:this.responseId,itemId:this.itemId,delta:e.outputTranscription.text,raw:t})),(null==(a=e.inputTranscription)?void 0:a.text)&&i.push({type:"input-transcription-completed",itemId:`google-input-${this.turnCounter}`,transcript:e.inputTranscription.text,raw:t}),e.generationComplete&&i.push({type:"custom",rawType:"generationComplete",raw:t}),e.turnComplete&&(this.hasAudio&&i.push({type:"audio-done",responseId:this.responseId,itemId:this.itemId,raw:t}),this.hasText&&i.push({type:"text-done",responseId:this.responseId,itemId:this.itemId,raw:t}),this.hasTranscript&&i.push({type:"audio-transcript-done",responseId:this.responseId,itemId:this.itemId,raw:t}),i.push({type:"response-done",responseId:this.responseId,status:"completed",raw:t}),this.turnClosed=!0),0===i.length)?{type:"custom",rawType:"serverContent",raw:t}:1===i.length?i[0]:i}serializeClientEvent(e,t){var o;switch(e.type){case"session-update":return(null==(o=e.config.inputAudioFormat)?void 0:o.rate)!=null&&(this.inputAudioRate=e.config.inputAudioFormat.rate),{setup:te(e.config,t)};case"input-audio-append":return{realtimeInput:{audio:{data:e.audio,mimeType:`audio/pcm;rate=${this.inputAudioRate}`}}};case"input-audio-commit":return{realtimeInput:{audioStreamEnd:!0}};case"input-audio-clear":case"response-create":case"response-cancel":case"conversation-item-truncate":break;case"conversation-item-create":{let t=e.item;switch(t.type){case"text-message":return{realtimeInput:{text:t.text}};case"function-call-output":return e7(t);case"audio-message":return null}}}return null}};async function e7(e){let o=await (0,t.safeParseJSON)({text:e.output}),n=o.success?o.value:{};return{toolResponse:{functionResponses:[{id:e.callId,name:e.name,response:n}]}}}function te(e,o){let n={model:p(o)},r={};if((null==e?void 0:e.outputModalities)!=null?r.responseModalities=e.outputModalities.map(e=>e.toUpperCase()):r.responseModalities=["AUDIO"],(null==e?void 0:e.voice)!=null&&(r.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.voice}}}),n.generationConfig=r,(null==e?void 0:e.instructions)!=null&&(n.systemInstruction={parts:[{text:e.instructions}]}),(null==e?void 0:e.tools)!=null&&e.tools.length>0&&(n.tools=[{functionDeclarations:e.tools.map(e=>({name:e.name,description:e.description,parameters:g(e.parameters)}))}]),(null==e?void 0:e.inputAudioTranscription)!=null&&(n.inputAudioTranscription={}),(null==e?void 0:e.outputAudioTranscription)!=null&&(n.outputAudioTranscription={}),(null==e?void 0:e.providerOptions)==null)return n;let{google:a,...i}=e.providerOptions;Object.assign(n,i);let l=(0,t.isRecord)(a)?a:void 0;if((null==l?void 0:l.translationConfig)!=null){let e=(0,t.isRecord)(n.generationConfig)?n.generationConfig:r;n.generationConfig={...e,translationConfig:l.translationConfig}}return n}var tt=class{constructor(e,t){this.specificationVersion="v4",this.mapper=new e9,this.modelId=e,this.provider=t.provider,this.config=t}async doCreateClientSecret(e){var t,o;let n,r=null!=(t=this.config.fetch)?t:fetch,a=this.config.headers()["x-goog-api-key"];if(!a)throw Error("Google Generative AI API key is required for realtime token creation.");let i=Date.now(),l=(null!=(o=e.expiresAfterSeconds)?o:60)*1e3,s=new Date(i+l).toISOString(),u=new Date(i+l+18e5).toISOString(),c=te(e.sessionConfig,this.modelId),d=await r(`${((n=e5(this.config.baseURL)).pathname=`${n.pathname.replace(/\/$/,"")}/v1alpha/auth_tokens`,n.toString())}?key=${encodeURIComponent(a)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uses:0,expireTime:u,newSessionExpireTime:s,bidiGenerateContentSetup:c})});if(!d.ok){let e=await d.text();throw Error(`Google realtime auth token request failed: ${d.status} ${e}`)}let p=await d.json();return{token:p.name,url:e8(this.config.baseURL,"google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained").toString(),expiresAt:p.expireTime?Math.floor(new Date(p.expireTime).getTime()/1e3):void 0}}getWebSocketConfig(e){return{url:`${e.url}?access_token=${encodeURIComponent(e.token)}`}}parseServerEvent(e){return this.mapper.parseServerEvent(e)}serializeClientEvent(e){return this.mapper.serializeClientEvent(e,this.modelId)}buildSessionConfig(e){return te(e,this.modelId)}},to=r.z.object({languageCodes:r.z.array(r.z.string()).optional(),customVocabulary:r.z.array(r.z.string()).optional(),wordTimestamp:r.z.boolean().optional(),diarization:r.z.boolean().optional(),mode:r.z.enum(["SMART","VERBATIM"]).optional()});function tn(e){return e.includes("-live")}var tr=class e{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v4"}static[n.WORKFLOW_SERIALIZE](e){return(0,t.serializeModelOptions)({modelId:e.modelId,config:e.config})}static[n.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async parseOptions(e){return(0,t.parseProviderOptions)({provider:"google",providerOptions:e,schema:to})}async doGenerate(e){var n,r,a,l,s,u;if(tn(this.modelId))throw new o.InvalidArgumentError({argument:"modelId",message:`Model '${this.modelId}' only supports streaming transcription. Use experimental_streamTranscribe, or a unary model such as 'gemini-3.5-transcribe'.`});let c=null!=(a=null==(r=null==(n=this.config._internal)?void 0:n.currentDate)?void 0:r.call(n))?a:new Date,d=function(e){var t;if(null==e)return;let o={};return null!=e.languageCodes&&(o.language_codes=e.languageCodes),null!=e.customVocabulary&&(o.custom_vocabulary=e.customVocabulary),(null!=e.mode||!0===e.diarization||!0===e.wordTimestamp)&&(o.mode={type:(null!=(t=e.mode)?t:"VERBATIM").toLowerCase(),...!0===e.diarization?{diarization_mode:"speaker"}:{},...!0===e.wordTimestamp?{timestamp_granularities:["word"]}:{}}),Object.keys(o).length>0?o:void 0}(await this.parseOptions(e.providerOptions)),p={model:this.modelId,input:[{type:"audio",data:(0,t.convertToBase64)(e.audio),mime_type:e.mediaType}],...null!=d?{generation_config:{transcription_config:d}}:{}},{value:m,responseHeaders:h,rawValue:g}=await (0,t.postJsonToApi)({url:`${this.config.baseURL}/interactions`,headers:(0,t.combineHeaders)(this.config.headers?await (0,t.resolve)(this.config.headers):void 0,e.headers),body:p,failedResponseHandler:i,successfulResponseHandler:(0,t.createJsonResponseHandler)(tl),abortSignal:e.abortSignal,fetch:this.config.fetch}),f="",y=[];for(let e of null!=(l=m.steps)?l:[])for(let t of null!=(s=e.content)?s:[])if("text"===t.type&&null!=t.text)for(let e of(f+=t.text,null!=(u=t.annotations)?u:[])){if("word_info"!==e.type)continue;let t=ta(e.start_offset),o=ta(e.end_offset);null!=e.text&&null!=t&&null!=o&&y.push({text:e.text,startSecond:t,endSecond:o})}return{text:f,segments:y,language:void 0,durationInSeconds:void 0,warnings:[],response:{timestamp:c,modelId:this.modelId,headers:h,body:g},...null!=m.usage?{providerMetadata:{google:{usage:m.usage}}}:{}}}async doStream(e){let n,r;if(!tn(this.modelId))throw new o.InvalidArgumentError({argument:"modelId",message:`Model '${this.modelId}' does not support streaming transcription. Use a live model such as 'gemini-3.5-transcribe-live'.`});let a=null!=(u=null==(s=null==(l=this.config._internal)?void 0:l.currentDate)?void 0:s.call(l))?u:new Date,i=await this.parseOptions(e.providerOptions);var l,s,u,c,d,m,h,g,f,y=e.inputAudioFormat;if("audio/pcm"!==y.type||null!=y.rate&&16e3!==y.rate)throw new o.InvalidArgumentError({argument:"inputAudioFormat",message:"The Gemini Live transcription API only supports 16kHz 16-bit PCM input audio."});let v=(0,t.combineHeaders)(this.config.headers?await (0,t.resolve)(this.config.headers):void 0,e.headers);for(let[e,t]of Object.entries(v))"x-goog-api-key"===e.toLowerCase()&&null!=t&&(n=t);if(null==n)throw Error("Google Generative AI API key is required for streaming transcription.");let _=Object.fromEntries(Object.entries(v).filter(([e])=>"x-goog-api-key"!==e.toLowerCase())),b={model:p(this.modelId),inputAudioTranscription:null!=(c=function(e){if(null==e)return;let t={};return null!=e.languageCodes&&(t.languageCodes=e.languageCodes),null!=e.customVocabulary&&(t.customVocabulary=e.customVocabulary),null!=e.wordTimestamp&&(t.wordTimestamp=e.wordTimestamp),null!=e.diarization&&(t.diarization=e.diarization),null!=e.mode&&(t.mode=e.mode),Object.keys(t).length>0?t:void 0}(i))?c:{}};return{request:{body:b},response:{timestamp:a,modelId:this.modelId},stream:function({webSocket:e,url:o,headers:n,setup:r,inputAudioRate:a,finishGraceMs:i,warnings:l,audio:s,abortSignal:u,includeRawChunks:c}){let d=!1,p=()=>{};return new ReadableStream({start:m=>{let h,g,f,y,v,_,b=new Promise(e=>{f=e}),z=0,w="",x="",S="",k=!1,I=()=>`google-segment-${z}`,T=()=>{null!=_&&(clearTimeout(_),_=void 0)},C=()=>{!d&&k&&(T(),_=setTimeout(()=>{_=void 0,j()},i))};p=e=>{T(),null!=h?h.cancel().catch(()=>{}):s.cancel().catch(()=>{}),null==g||g.close(e)};let E=e=>{d||(d=!0,p(),m.error(e))},M=()=>{if(""===w){if(""===S)return;w=S}S="",m.enqueue({type:"transcript-final",id:I(),text:w}),x+=""===x?w:` ${w}`,w="",z++},j=()=>{d||(M(),d=!0,m.enqueue({type:"finish",text:x,segments:[],language:y,durationInSeconds:void 0,...null!=v?{providerMetadata:{google:{usageMetadata:v}}}:{}}),m.close(),p(1e3))},A=async e=>{h=s.getReader();try{for(;;){let{done:o,value:n}=await h.read();if(o||d)break;e.send(JSON.stringify({realtimeInput:{audio:{data:(0,t.convertToBase64)(n),mimeType:`audio/pcm;rate=${a}`}}})),await (0,t.waitForWebSocketBufferDrain)(e)}}finally{h.releaseLock(),h=void 0}d||(e.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),k=!0,C())};g=(0,t.connectToWebSocket)({url:o,headers:n,webSocket:e,abortSignal:u,onAbort:E,onProcessingError:E,onOpen:e=>{m.enqueue({type:"stream-start",warnings:l}),e.send(JSON.stringify({setup:r})),b.then(()=>d?void 0:A(e)).catch(E)},onMessageText:async e=>{var o,n;if(d)return;let r=await (0,t.safeParseJSON)({text:e});if(!r.success)return;let a=r.value;if(c&&m.enqueue({type:"raw",rawValue:a}),null!=a.setupComplete&&f(),null!=a.usageMetadata&&(v=a.usageMetadata),null!=a.error)return void E(Error(null!=(o=a.error.message)?o:"Google Live API error"));let i=a.serverContent,l=null==i?void 0:i.interimInputTranscription;(null==l?void 0:l.text)&&(C(),S=l.text,m.enqueue({type:"transcript-partial",id:I(),text:l.text}));let s=null!=(n=null==i?void 0:i.inputTranscription)?n:a.inputTranscription;null!=s&&(null!=s.languageCode&&(y=s.languageCode),s.text&&(C(),S="",w+=s.text,m.enqueue({type:"transcript-delta",id:I(),delta:s.text})),!0===s.finished&&M()),(null==i?void 0:i.turnComplete)&&M();let u=null==i?void 0:i.interactionStatus;k&&("IDLE"===u||"REQUIRES_ACTION"===u||(null==i?void 0:i.turnComplete)===!0&&null==u)&&j()},onSocketError:()=>{E(Error("Google Live transcription error"))},onClose:({code:e,reason:t})=>{if(!d){if(k)return void j();E(Error(`Google Live transcription WebSocket closed unexpectedly before finishing (code ${null!=e?e:"unknown"}${t?`, reason: ${t}`:""}).`))}}})},cancel:()=>{d||(d=!0,p())}})}({webSocket:this.config.webSocket,url:(g=this.config.baseURL,f=n,(r=e8(g,"google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent")).searchParams.set("key",f),r),headers:_,setup:b,inputAudioRate:null!=(d=e.inputAudioFormat.rate)?d:16e3,finishGraceMs:null!=(h=null==(m=this.config._internal)?void 0:m.finishGraceMs)?h:3e3,warnings:[],audio:e.audio,abortSignal:e.abortSignal,includeRawChunks:e.includeRawChunks})}}};function ta(e){if(null==e)return;let t=Number.parseFloat(e);return Number.isFinite(t)?t:void 0}var ti=r.z.object({type:r.z.string().nullish(),text:r.z.string().nullish(),speaker:r.z.string().nullish(),start_offset:r.z.string().nullish(),end_offset:r.z.string().nullish()}),tl=r.z.object({status:r.z.string().nullish(),steps:r.z.array(r.z.object({type:r.z.string().nullish(),content:r.z.array(r.z.object({type:r.z.string().nullish(),text:r.z.string().nullish(),annotations:r.z.array(ti).nullish()})).nullish()})).nullish(),usage:r.z.record(r.z.string(),r.z.unknown()).nullish()}),ts=(0,t.lazySchema)(()=>(0,t.zodSchema)(r.z.object({echoTargetLanguage:r.z.boolean().optional()}))),tu=class e{constructor(e,t){this.specificationVersion="v4",this.modelId=e,this.config=t}static[n.WORKFLOW_SERIALIZE](e){return(0,t.serializeModelOptions)({modelId:e.modelId,config:e.config})}static[n.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doStream(e){var n,r,a,i,l,s,u,c;let d,m;if(null==e.targetLanguage)throw new o.InvalidArgumentError({argument:"targetLanguage",message:`targetLanguage is required for translation model '${this.modelId}'.`});let h=null!=(a=null==(r=null==(n=this.config._internal)?void 0:n.currentDate)?void 0:r.call(n))?a:new Date,g=await (0,t.parseProviderOptions)({provider:"google",providerOptions:e.providerOptions,schema:ts}),f=[];(function(e){if("audio/pcm"!==e.type||null!=e.rate&&16e3!==e.rate)throw new o.InvalidArgumentError({argument:"inputAudioFormat",message:"The Gemini Live translation API only supports 16kHz 16-bit PCM input audio."})})(e.inputAudioFormat),null!=e.sourceLanguage&&f.push({type:"unsupported",feature:"sourceLanguage",details:"The Gemini Live translation API auto-detects the source language and does not accept a source language."}),null!=e.outputAudioFormat&&f.push({type:"unsupported",feature:"outputAudioFormat",details:"The Gemini Live API always outputs 24kHz 16-bit PCM audio and does not accept an output audio format."});let y=(0,t.combineHeaders)(this.config.headers(),e.headers);for(let[e,t]of Object.entries(y))"x-goog-api-key"===e.toLowerCase()&&null!=t&&(d=t);if(null==d)throw Error("Google Generative AI API key is required for streaming translation.");let v=Object.fromEntries(Object.entries(y).filter(([e])=>"x-goog-api-key"!==e.toLowerCase())),_=function({modelId:e,targetLanguage:t,providerOptions:o}){return{model:p(e),generationConfig:{responseModalities:["AUDIO"],translationConfig:{targetLanguageCode:t,...(null==o?void 0:o.echoTargetLanguage)!=null?{echoTargetLanguage:o.echoTargetLanguage}:{}}},inputAudioTranscription:{},outputAudioTranscription:{}}}({modelId:this.modelId,targetLanguage:e.targetLanguage,providerOptions:g});return{request:{body:_},response:{timestamp:h,modelId:this.modelId},stream:function({webSocket:e,url:o,headers:n,setup:r,inputAudioRate:a,finishGraceMs:i,warnings:l,audio:s,abortSignal:u,includeRawChunks:c}){let d=!1,p=()=>{};return new ReadableStream({start:m=>{let h,g,f,y,v,_=new Promise(e=>{f=e}),b=0,z="",w="",x="",S="",k=!1,I=!1,T=!1,C=0,E=()=>`google-item-${b}`,M=()=>{null!=v&&(clearTimeout(v),v=void 0)},j=()=>{d||null!=v||(v=setTimeout(()=>{v=void 0,R()},i))},A=()=>{I=!0,C=0,M()};p=e=>{M(),null!=h?h.cancel().catch(()=>{}):s.cancel().catch(()=>{}),null==g||g.close(e)};let O=e=>{d||(d=!0,p(),m.error(e))},R=()=>{d||((""!==w||""!==S)&&N(),d=!0,m.enqueue({type:"finish",sourceText:z,outputText:x,usage:y}),m.close(),p(1e3))},N=()=>{""!==w&&(m.enqueue({type:"source-transcript-final",id:E(),text:w}),z+=w,w=""),""!==S&&(m.enqueue({type:"output-text-final",id:E(),text:S}),x+=S,S=""),b++},P=async e=>{h=s.getReader();try{for(;;){let{done:o,value:n}=await h.read();if(o||d)break;e.send(JSON.stringify({realtimeInput:{audio:{data:(0,t.convertToBase64)(n),mimeType:`audio/pcm;rate=${a}`}}})),await (0,t.waitForWebSocketBufferDrain)(e)}}finally{h.releaseLock(),h=void 0}d||(e.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),k=!0,T&&!I&&j())};g=(0,t.connectToWebSocket)({url:o,headers:n,webSocket:e,abortSignal:u,onAbort:O,onProcessingError:O,onOpen:e=>{m.enqueue({type:"stream-start",warnings:l}),e.send(JSON.stringify({setup:r})),_.then(()=>d?void 0:P(e)).catch(O)},onMessageText:async e=>{var o,n,r,a,l,s,u,p,h;if(d)return;let g=await (0,t.safeParseJSON)({text:e});if(!g.success)return;let v=g.value;if(c&&m.enqueue({type:"raw",rawValue:v}),null!=v.setupComplete&&f(),null!=v.usageMetadata&&(y=function(e,t){var o,n;let r=null==e?void 0:e.inputAudioTokens,a=null==e?void 0:e.outputAudioTokens;for(let e of null!=(o=t.promptTokensDetails)?o:[])"AUDIO"===e.modality&&null!=e.tokenCount&&(r=(null!=r?r:0)+e.tokenCount);for(let e of null!=(n=t.responseTokensDetails)?n:[])"AUDIO"===e.modality&&null!=e.tokenCount&&(a=(null!=a?a:0)+e.tokenCount);return null==r&&null==a?e:{...e,...null!=r?{inputAudioTokens:r}:{},...null!=a?{outputAudioTokens:a}:{}}}(y,v.usageMetadata)),null!=v.error)return void O(Error(null!=(o=v.error.message)?o:"Google Live API error"));let _=null!=(l=null==(r=null==(n=v.serverContent)?void 0:n.inputTranscription)?void 0:r.text)?l:null==(a=v.inputTranscription)?void 0:a.text;_&&(A(),w+=_,m.enqueue({type:"source-transcript-delta",id:E(),delta:_}));let b=v.serverContent;if(null!=b){for(let e of null!=(u=null==(s=b.modelTurn)?void 0:s.parts)?u:[])if(null==(p=e.inlineData)?void 0:p.data){m.enqueue({type:"audio",id:E(),audio:e.inlineData.data});let o=function(e){let o;try{o=(0,t.convertBase64ToUint8Array)(e)}catch(e){return}if(o.byteLength<2)return;let n=new DataView(o.buffer,o.byteOffset,o.byteLength),r=Math.floor(o.byteLength/2);for(let e=0;e<r;e++)if(Math.abs(n.getInt16(2*e,!0))>128)return;return r/24e3*1e3}(e.inlineData.data);if(k&&null!=o){if((C+=o)>=i)return void R()}else A()}(null==(h=b.outputTranscription)?void 0:h.text)&&(A(),S+=b.outputTranscription.text,m.enqueue({type:"output-text-delta",id:E(),delta:b.outputTranscription.text})),b.turnComplete&&(N(),I=!1,T=!0,k&&j())}},onSocketError:()=>{O(Error("Google Live translation error"))},onClose:({code:e,reason:t})=>{if(!d){if(null!=v)return void R();O(Error(`Google Live translation WebSocket closed unexpectedly before finishing (code ${null!=e?e:"unknown"}${t?`, reason: ${t}`:""}).`))}}})},cancel:()=>{d||(d=!0,p())}})}({webSocket:this.config.webSocket,url:(u=this.config.baseURL,c=d,(m=e8(u,"google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent")).searchParams.set("key",c),m),headers:v,setup:_,inputAudioRate:null!=(i=e.inputAudioFormat.rate)?i:16e3,finishGraceMs:null!=(s=null==(l=this.config._internal)?void 0:l.finishGraceMs)?s:1e3,warnings:f,audio:e.audio,abortSignal:e.abortSignal,includeRawChunks:e.includeRawChunks})}}},tc=/^https:\/\/generativelanguage\.googleapis\.com\/v1beta\/files\/.*$/,td=["text/html","text/css","text/plain","text/xml","text/csv","text/rtf","text/javascript","application/json","application/pdf","image/bmp","image/jpeg","image/png","image/webp","video/mp4","video/mpeg","video/quicktime","video/avi","video/x-flv","video/mpg","video/webm","video/wmv","video/3gpp"],tp=/^https:\/\/.*$/;function tm(e={}){var o,n;let r=null!=(o=(0,t.withoutTrailingSlash)(e.baseURL))?o:"https://generativelanguage.googleapis.com/v1beta",a=null!=(n=e.name)?n:"google.generative-ai",i=()=>(0,t.withUserAgentSuffix)({"x-goog-api-key":(0,t.loadApiKey)({apiKey:e.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...e.headers},"ai-sdk/google/4.0.64"),l=o=>{var n;return new X(o,{provider:a,baseURL:r,headers:i,generateId:null!=(n=e.generateId)?n:t.generateId,supportedUrls:()=>({"*":[tc,RegExp(`^${r}/files/.*$`),RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")],.../(^|\/)gemini-/.test(o)&&!/(^|\/)gemini-2\.0/.test(o)?Object.fromEntries(td.map(e=>[e,[tp]])):{}}),fetch:e.fetch})},s=t=>new u(t,{provider:a,baseURL:r,headers:i,fetch:e.fetch}),c=(t,o={})=>new ec(t,o,{provider:a,baseURL:r,headers:i,fetch:e.fetch}),d=o=>{var n;return new ey(o,{provider:a,baseURL:r,headers:i,fetch:e.fetch,generateId:null!=(n=e.generateId)?n:t.generateId})},p=t=>new tt(t,{provider:`${a}.realtime`,baseURL:r,headers:i,fetch:e.fetch}),m=t=>new tu(t,{provider:`${a}.speech-translation`,baseURL:r,headers:i,webSocket:e.webSocket}),h=t=>new eS(t,{provider:`${a}.speech`,baseURL:r,headers:i,fetch:e.fetch}),g=t=>new tr(t,{provider:`${a}.transcription`,baseURL:r,headers:i,fetch:e.fetch,webSocket:e.webSocket}),f=Object.assign(e=>p(e),{getToken:async e=>{let t=p(e.model),o=await t.doCreateClientSecret({sessionConfig:e.sessionConfig,expiresAfterSeconds:e.expiresAfterSeconds});return{token:o.token,url:o.url,expiresAt:o.expiresAt}}}),y=function(e){if(new.target)throw Error("The Google Generative AI model function cannot be called with the new keyword.");return l(e)};return y.specificationVersion="v4",y.languageModel=l,y.chat=l,y.generativeAI=l,y.embedding=s,y.embeddingModel=s,y.textEmbedding=s,y.textEmbeddingModel=s,y.image=c,y.imageModel=c,y.video=d,y.videoModel=d,y.experimental_realtime=f,y.files=()=>new ep({provider:a,baseURL:r,headers:i,fetch:e.fetch}),y.speech=h,y.speechModel=h,y.transcription=g,y.transcriptionModel=g,y.translation=m,y.speechTranslationModel=m,y.interactions=o=>{var n;return new e3(o,{provider:`${a}.interactions`,baseURL:r,headers:i,generateId:null!=(n=e.generateId)?n:t.generateId,fetch:e.fetch})},y.tools=es,y}tm(),e.s(["createGoogleGenerativeAI",0,tm])},970354,e=>{"use strict";var t,o=e.i(691296),n=e.i(548874),r=e.i(853205),a=e.i(296194),i=r.z.object({error:r.z.object({message:r.z.string(),type:r.z.string().nullish(),param:r.z.any().nullish(),code:r.z.union([r.z.string(),r.z.number()]).nullish()})}),l=(0,o.createJsonErrorResponseHandler)({errorSchema:i,errorToMessage:e=>e.error.message});function s(e){var t,o,n,r,a,i;let l,s=(i=e,null==(l=/^o(\d+)(?:-|$)/.exec(i))?void 0:Number(l[1])),u=function(e){let t=/^gpt-(\d+)(?:\.(\d+))?(?:-(.+))?$/.exec(e);if(null!=t)return{major:Number(t[1]),minor:null==t[2]?void 0:Number(t[2]),variant:t[3]}}(e),c=(null==u?void 0:u.minor)==null&&null!=(o=null==(t=null==u?void 0:u.variant)?void 0:t.startsWith("chat"))&&o,d=null!=(r=null==(n=null==u?void 0:u.variant)?void 0:n.startsWith("nano"))&&r,p=null!=u&&u.major>=6,m=null!=s&&s>=3||null!=u&&u.major>=5&&!c,h=e.startsWith("gpt-4")||null!=u&&u.major>=5&&!d&&!c||null!=s&&s>=3,g=null!=s||null!=u&&u.major>=5&&!c,f=!p&&null!=u&&(u.major>5||5===u.major&&(null!=(a=u.minor)?a:0)>=1);return{supportsFlexProcessing:m,supportsPriorityProcessing:h,supportsConfigurationUpdate:p,supportedReasoningEfforts:p?["low","medium","high","xhigh","max"]:void 0,isReasoningModel:g,systemMessageMode:g?"developer":"system",supportsNonReasoningParameters:f}}function u(e){var t,n;let r=function(e){var t;let o=m(e);if(null==o)return;if("response.failed"===o.type){let e=m(o.response),t=m(null==e?void 0:e.error);return"string"==typeof(null==t?void 0:t.message)?{message:t.message,code:h(t.code),type:"response.failed"}:void 0}let n=null!=(t=m(o.error))?t:o;return"string"==typeof n.message&&(null!=m(o.error)||"string"==typeof n.type||"code"in n||"param"in n)?{message:n.message,code:h(n.code),type:"string"==typeof n.type?n.type:void 0}:void 0}(e);if(null==r)return;let a=function(e){var t,o;let n,r="number"==typeof(n="string"==typeof(t=e.code)&&/^\d{3}$/.test(t)?Number(t):t)&&Number.isInteger(o=n)&&o>=400&&o<=599?n:void 0;if(null!=r)return r;let a=[e.code,e.type].filter(e=>"string"==typeof e||"number"==typeof e).join(" ").toLowerCase();return["insufficient_quota","rate_limit"].some(e=>a.includes(e))?429:a.includes("authentication")?401:a.includes("permission")?403:a.includes("not_found")?404:["invalid","bad_request","context_length"].some(e=>a.includes(e))?400:a.includes("overload")?503:a.includes("timeout")?504:500}(r);return(0,o.createProviderStreamError)({message:r.message,type:null!=(t=r.type)?t:void 0,code:null!=(n=r.code)?n:void 0,statusCode:a,isRetryable:function(e,t){return"insufficient_quota"!==e.code&&"insufficient_quota"!==e.type&&(408===t||409===t||429===t||t>=500)}(r,a),data:e})}async function c({stream:e,getError:t,isOutputChunk:o,isAcceptedChunk:n,acceptedGraceMs:r=50,url:i,requestBodyValues:l,responseHeaders:s}){let[m,h]=e.tee(),g=m.getReader(),f=!1;try{let e=!1;for(;;){let c;if(e){let e=await p(g.read(),r);if(e.timedOut)return h;c=e.value}else c=await g.read();if(c.done)return h;let m=c.value;if(!m.success)return h;let y=t(m.value);if(null!=y)throw f=!0,d(g).catch(()=>{}),d(h.getReader()).catch(()=>{}),function({frame:e,url:t,requestBodyValues:o,responseHeaders:n}){var r,i;let l=u(e);return new a.APICallError({message:null!=(r=null==l?void 0:l.message)?r:"OpenAI stream failed before any output was generated",url:t,requestBodyValues:o,statusCode:null!=(i=null==l?void 0:l.statusCode)?i:500,responseHeaders:n,responseBody:JSON.stringify(e),data:e,isRetryable:null==l?void 0:l.isRetryable})}({frame:y,url:i,requestBodyValues:l,responseHeaders:s});if(o(m.value))return h;e||(null==n?void 0:n(m.value))!==!0||(e=!0)}}finally{f||(g.cancel().catch(()=>{}),g.releaseLock())}}async function d(e){try{for(;!(await e.read()).done;);}catch(e){}finally{e.releaseLock()}}async function p(e,t){let o,n=e.then(e=>({timedOut:!1,value:e}));try{let e=await Promise.race([n,new Promise(e=>{o=setTimeout(()=>e({timedOut:!0}),t)})]);return e.timedOut&&n.catch(()=>{}),e}finally{clearTimeout(o)}}function m(e){return"object"==typeof e&&null!=e?e:void 0}function h(e){return"string"==typeof e||"number"==typeof e?e:void 0}function g(e){var t,n,r,a,i,l,s,u;if(null==e)return(0,o.createNullLanguageModelUsage)();let c=null!=(t=e.prompt_tokens)?t:0,d=null!=(n=e.completion_tokens)?n:0,p=null!=(a=null==(r=e.prompt_tokens_details)?void 0:r.cached_tokens)?a:0,m=null!=(l=null==(i=e.prompt_tokens_details)?void 0:i.cache_write_tokens)?l:void 0,h=null!=(u=null==(s=e.completion_tokens_details)?void 0:s.reasoning_tokens)?u:0;return{inputTokens:{total:c,noCache:c-p-(null!=m?m:0),cacheRead:p,cacheWrite:m},outputTokens:{total:d,text:Math.max(0,d-h),reasoning:h},raw:e}}function f(e){var t;return null==(t=null==e?void 0:e.openai)?void 0:t.promptCacheBreakpoint}function y({id:e,model:t,created:n}){return(0,o.createLanguageModelResponseMetadata)({id:e,model:t,created:n||void 0})}function v(e){switch(e){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"}}var _=(0,o.lazySchema)(()=>(0,o.zodSchema)(r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({message:r.z.object({role:r.z.literal("assistant").nullish(),content:r.z.string().nullish(),tool_calls:r.z.array(r.z.object({id:r.z.string().nullish(),type:r.z.literal("function"),function:r.z.object({name:r.z.string(),arguments:r.z.string()})})).nullish(),annotations:r.z.array(r.z.object({type:r.z.literal("url_citation"),url_citation:r.z.object({start_index:r.z.number(),end_index:r.z.number(),url:r.z.string(),title:r.z.string()})})).nullish()}),index:r.z.number(),logprobs:r.z.object({content:r.z.array(r.z.object({token:r.z.string(),logprob:r.z.number(),top_logprobs:r.z.array(r.z.object({token:r.z.string(),logprob:r.z.number()}))})).nullish()}).nullish(),finish_reason:r.z.string().nullish()})),usage:r.z.object({prompt_tokens:r.z.number().nullish(),completion_tokens:r.z.number().nullish(),total_tokens:r.z.number().nullish(),prompt_tokens_details:r.z.object({cached_tokens:r.z.number().nullish(),cache_write_tokens:r.z.number().nullish()}).nullish(),completion_tokens_details:r.z.object({reasoning_tokens:r.z.number().nullish(),accepted_prediction_tokens:r.z.number().nullish(),rejected_prediction_tokens:r.z.number().nullish()}).nullish()}).nullish()}))),b=(0,o.lazySchema)(()=>(0,o.zodSchema)(r.z.union([r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({delta:r.z.object({role:r.z.enum(["assistant"]).nullish(),content:r.z.string().nullish(),tool_calls:r.z.array(r.z.object({index:r.z.number(),id:r.z.string().nullish(),type:r.z.literal("function").nullish(),function:r.z.object({name:r.z.string().nullish(),arguments:r.z.string().nullish()})})).nullish(),annotations:r.z.array(r.z.object({type:r.z.literal("url_citation"),url_citation:r.z.object({start_index:r.z.number(),end_index:r.z.number(),url:r.z.string(),title:r.z.string()})})).nullish()}).nullish(),logprobs:r.z.object({content:r.z.array(r.z.object({token:r.z.string(),logprob:r.z.number(),top_logprobs:r.z.array(r.z.object({token:r.z.string(),logprob:r.z.number()}))})).nullish()}).nullish(),finish_reason:r.z.string().nullish(),index:r.z.number()})),usage:r.z.object({prompt_tokens:r.z.number().nullish(),completion_tokens:r.z.number().nullish(),total_tokens:r.z.number().nullish(),prompt_tokens_details:r.z.object({cached_tokens:r.z.number().nullish(),cache_write_tokens:r.z.number().nullish()}).nullish(),completion_tokens_details:r.z.object({reasoning_tokens:r.z.number().nullish(),accepted_prediction_tokens:r.z.number().nullish(),rejected_prediction_tokens:r.z.number().nullish()}).nullish()}).nullish()}),i]))),z=(0,o.lazySchema)(()=>(0,o.zodSchema)(r.z.object({logitBias:r.z.record(r.z.coerce.number(),r.z.number()).optional(),logprobs:r.z.union([r.z.boolean(),r.z.number()]).optional(),parallelToolCalls:r.z.boolean().optional(),user:r.z.string().optional(),reasoningEffort:r.z.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),maxCompletionTokens:r.z.number().optional(),store:r.z.boolean().optional(),metadata:r.z.record(r.z.string().max(64),r.z.string().max(512)).optional(),prediction:r.z.record(r.z.string(),r.z.any()).optional(),serviceTier:r.z.enum(["auto","flex","priority","fast","ultrafast","default"]).optional(),strictJsonSchema:r.z.boolean().optional(),textVerbosity:r.z.enum(["low","medium","high"]).optional(),promptCacheKey:r.z.string().optional(),promptCacheOptions:r.z.object({mode:r.z.enum(["implicit","explicit"]).optional(),ttl:r.z.literal("30m").optional()}).optional(),promptCacheRetention:r.z.enum(["in_memory","24h"]).optional(),safetyIdentifier:r.z.string().optional(),systemMessageMode:r.z.enum(["system","developer","remove"]).optional(),forceReasoning:r.z.boolean().optional()}))),w=class e{constructor(e,t){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}static[n.WORKFLOW_SERIALIZE](e){return(0,o.serializeModelOptions)({modelId:e.modelId,config:e.config})}static[n.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:l,presencePenalty:u,stopSequences:c,responseFormat:d,seed:p,tools:m,toolChoice:h,reasoning:g,providerOptions:y}){var v,_,b,w,x,S;let k=[],I=null!=(v=await (0,o.parseProviderOptions)({provider:"openai",providerOptions:y,schema:z}))?v:{},T=s(this.modelId),C=null!=(_=I.reasoningEffort)?_:(0,o.isCustomReasoning)(g)?g:void 0;null==C||null==T.supportedReasoningEfforts||T.supportedReasoningEfforts.includes(C)||(k.push({type:"unsupported",feature:"reasoningEffort",details:`${this.modelId} only supports the following reasoning efforts: ${T.supportedReasoningEfforts.join(", ")}`}),C=void 0);let E=null!=(b=I.forceReasoning)?b:T.isReasoningModel;null!=i&&k.push({type:"unsupported",feature:"topK"});let{messages:M,warnings:j}=function({prompt:e,systemMessageMode:t="system"}){var n,r,i;let l=[],s=[];for(let{role:u,content:c,providerOptions:d}of e)switch(u){case"system":switch(t){case"system":{let e=f(d);l.push({role:"system",content:null==e?c:[{type:"text",text:c,prompt_cache_breakpoint:e}]});break}case"developer":{let e=f(d);l.push({role:"developer",content:null==e?c:[{type:"text",text:c,prompt_cache_breakpoint:e}]});break}case"remove":s.push({type:"other",message:"system messages are removed for this model"});break;default:throw Error(`Unsupported system message mode: ${t}`)}break;case"user":if(1===c.length&&"text"===c[0].type&&null==f(c[0].providerOptions)){l.push({role:"user",content:c[0].text});break}l.push({role:"user",content:c.map((e,t)=>{var n,r,i;switch(e.type){case"text":{let t=f(e.providerOptions);return{type:"text",text:e.text,...null!=t&&{prompt_cache_breakpoint:t}}}case"file":{let l=f(e.providerOptions);switch(e.data.type){case"reference":return{type:"file",file:{file_id:(0,o.resolveProviderReference)({reference:e.data.reference,provider:"openai"})},...null!=l&&{prompt_cache_breakpoint:l}};case"text":throw new a.UnsupportedFunctionalityError({functionality:"text file parts"});case"url":case"data":{let s=(0,o.getTopLevelMediaType)(e.mediaType);if("image"===s)return{type:"image_url",image_url:{url:"url"===e.data.type?e.data.url.toString():`data:${(0,o.resolveFullMediaType)({part:e})};base64,${(0,o.convertToBase64)(e.data.data)}`,detail:null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.imageDetail},...null!=l&&{prompt_cache_breakpoint:l}};if("audio"===s){if("url"===e.data.type)throw new a.UnsupportedFunctionalityError({functionality:"audio file parts with URLs"});let t=(0,o.resolveFullMediaType)({part:e});switch(t){case"audio/wav":return{type:"input_audio",input_audio:{data:(0,o.convertToBase64)(e.data.data),format:"wav"},...null!=l&&{prompt_cache_breakpoint:l}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:(0,o.convertToBase64)(e.data.data),format:"mp3"},...null!=l&&{prompt_cache_breakpoint:l}};default:throw new a.UnsupportedFunctionalityError({functionality:`audio content parts with media type ${t}`})}}{let n=(0,o.resolveFullMediaType)({part:e});if("application/pdf"!==n)throw new a.UnsupportedFunctionalityError({functionality:`file part media type ${n}`});if("url"===e.data.type)throw new a.UnsupportedFunctionalityError({functionality:"PDF file parts with URLs"});return{type:"file",file:{filename:null!=(i=e.filename)?i:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${(0,o.convertToBase64)(e.data.data)}`},...null!=l&&{prompt_cache_breakpoint:l}}}}}}}})});break;case"assistant":{let e="",t=[],o=!1,n=[];for(let r of c)switch(r.type){case"text":{let n=f(r.providerOptions);e+=r.text,t.push({type:"text",text:r.text,...null!=n&&{prompt_cache_breakpoint:n}}),o||(o=null!=n);break}case"tool-call":n.push({id:r.toolCallId,type:"function",function:{name:r.toolName,arguments:JSON.stringify("object"!=typeof(i=r.input)||null===i||Array.isArray(i)?{}:i)}})}l.push({role:"assistant",content:o?t:n.length>0?e||null:e,tool_calls:n.length>0?n:void 0});break}case"tool":for(let e of c){let t;if("tool-approval-response"===e.type)continue;let o=e.output,a=null!=(n="content"===o.type?o.value.map(e=>f(e.providerOptions)).find(e=>null!=e):f(o.providerOptions))?n:f(e.providerOptions);switch(o.type){case"text":case"error-text":t=o.value;break;case"execution-denied":t=null!=(r=o.reason)?r:"Tool call execution denied.";break;case"content":case"json":case"error-json":t=JSON.stringify(o.value)}l.push({role:"tool",tool_call_id:e.toolCallId,content:null==a?t:[{type:"text",text:t,prompt_cache_breakpoint:a}]})}break;default:throw Error(`Unsupported role: ${u}`)}return{messages:l,warnings:s}}({prompt:e,systemMessageMode:null!=(w=I.systemMessageMode)?w:E?"developer":T.systemMessageMode});k.push(...j);let A=null==(x=I.strictJsonSchema)||x,O={model:this.modelId,logit_bias:I.logitBias,logprobs:!0===I.logprobs||"number"==typeof I.logprobs||void 0,top_logprobs:"number"==typeof I.logprobs?I.logprobs:"boolean"==typeof I.logprobs&&I.logprobs?0:void 0,user:I.user,parallel_tool_calls:I.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:l,presence_penalty:u,response_format:(null==d?void 0:d.type)==="json"?null!=d.schema?{type:"json_schema",json_schema:{schema:d.schema,strict:A,name:null!=(S=d.name)?S:"response",description:d.description}}:{type:"json_object"}:void 0,stop:c,seed:p,verbosity:I.textVerbosity,max_completion_tokens:I.maxCompletionTokens,store:I.store,metadata:I.metadata,prediction:I.prediction,reasoning_effort:C,service_tier:I.serviceTier,prompt_cache_key:I.promptCacheKey,prompt_cache_options:I.promptCacheOptions,prompt_cache_retention:I.promptCacheRetention,safety_identifier:I.safetyIdentifier,messages:M};null!=T.supportedReasoningEfforts&&null!=O.prompt_cache_retention&&(O.prompt_cache_retention=void 0,k.push({type:"unsupported",feature:"promptCacheRetention",details:"promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"})),E?("none"===C&&T.supportsNonReasoningParameters||(null!=O.temperature&&(O.temperature=void 0,k.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),null!=O.top_p&&(O.top_p=void 0,k.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),null!=O.logprobs&&(O.logprobs=void 0,k.push({type:"other",message:"logprobs is not supported for reasoning models"}))),null!=O.frequency_penalty&&(O.frequency_penalty=void 0,k.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),null!=O.presence_penalty&&(O.presence_penalty=void 0,k.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),null!=O.logit_bias&&(O.logit_bias=void 0,k.push({type:"other",message:"logitBias is not supported for reasoning models"})),null!=O.top_logprobs&&(O.top_logprobs=void 0,k.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),null!=O.max_tokens&&(null==O.max_completion_tokens&&(O.max_completion_tokens=O.max_tokens),O.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&null!=O.temperature&&(O.temperature=void 0,k.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),"flex"!==I.serviceTier||T.supportsFlexProcessing||(k.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),O.service_tier=void 0),"priority"!==I.serviceTier&&"fast"!==I.serviceTier||T.supportsPriorityProcessing||(k.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),O.service_tier=void 0);let{tools:R,toolChoice:N,toolWarnings:P}=function({tools:e,toolChoice:t}){e=(null==e?void 0:e.length)?e:void 0;let o=[];if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:o};let n=[];for(let t of e)"function"===t.type?n.push({type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema,...null!=t.strict?{strict:t.strict}:{}}}):o.push({type:"unsupported",feature:`tool type: ${t.type}`});if(null==t)return{tools:n,toolChoice:void 0,toolWarnings:o};let r=t.type;switch(r){case"auto":case"none":case"required":return{tools:n,toolChoice:r,toolWarnings:o};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:throw new a.UnsupportedFunctionalityError({functionality:`tool choice type: ${r}`})}}({tools:m,toolChoice:h});return{args:{...O,tools:R,tool_choice:N},warnings:[...k,...P]}}async doGenerate(e){var t,n,r,a,i,s,u;let{args:c,warnings:d}=await this.getArgs(e),{responseHeaders:p,value:m,rawValue:h}=await (0,o.postJsonToApi)({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:(0,o.combineHeaders)(null==(n=(t=this.config).headers)?void 0:n.call(t),e.headers),body:c,failedResponseHandler:l,successfulResponseHandler:(0,o.createJsonResponseHandler)(_),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=m.choices[0],b=[],z=f.message.content;for(let e of(null!=z&&z.length>0&&b.push({type:"text",text:z}),null!=(r=f.message.tool_calls)?r:[]))b.push({type:"tool-call",toolCallId:e.id||(0,o.generateId)(),toolName:e.function.name,input:e.function.arguments});for(let e of null!=(a=f.message.annotations)?a:[])b.push({type:"source",sourceType:"url",id:(0,o.generateId)(),url:e.url_citation.url,title:e.url_citation.title});let w=null==(i=m.usage)?void 0:i.completion_tokens_details,x={openai:{}};return(null==w?void 0:w.accepted_prediction_tokens)!=null&&(x.openai.acceptedPredictionTokens=null==w?void 0:w.accepted_prediction_tokens),(null==w?void 0:w.rejected_prediction_tokens)!=null&&(x.openai.rejectedPredictionTokens=null==w?void 0:w.rejected_prediction_tokens),(null==(s=f.logprobs)?void 0:s.content)!=null&&(x.openai.logprobs=f.logprobs.content),{content:b,finishReason:{unified:v(f.finish_reason),raw:null!=(u=f.finish_reason)?u:void 0},usage:g(m.usage),request:{body:c},response:{...y(m),headers:p,body:h},warnings:d,providerMetadata:x}}async doStream(e){var t,n;let r,a,{args:i,warnings:s}=await this.getArgs(e),d={...i,stream:!0,stream_options:{include_usage:!0}},p=this.config.url({path:"/chat/completions",modelId:this.modelId}),{responseHeaders:m,value:h}=await (0,o.postJsonToApi)({url:p,headers:(0,o.combineHeaders)(null==(n=(t=this.config).headers)?void 0:n.call(t),e.headers),body:d,failedResponseHandler:l,successfulResponseHandler:(0,o.createEventSourceResponseHandler)(b),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=await c({stream:h,getError:e=>"error"in e?e.error:void 0,isOutputChunk:x,url:p,requestBodyValues:d,responseHeaders:m}),_={unified:"other",raw:void 0},z=!1,w=!1,S={openai:{}};return{stream:f.pipeThrough(new TransformStream({start(e){r=new o.StreamingToolCallTracker(e,{generateId:o.generateId,typeValidation:"if-present"}),e.enqueue({type:"stream-start",warnings:s})},transform(t,n){var i,l,s,c,d,p;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success){_={unified:"error",raw:void 0},n.enqueue({type:"error",error:t.error});return}let m=t.value;if("error"in m){_={unified:"error",raw:void 0},n.enqueue({type:"error",error:null!=(i=u(m.error))?i:m.error});return}!z&&Object.values(y(m)).some(Boolean)&&(z=!0,n.enqueue({type:"response-metadata",...y(m)})),null!=m.usage&&(a=m.usage,(null==(l=m.usage.completion_tokens_details)?void 0:l.accepted_prediction_tokens)!=null&&(S.openai.acceptedPredictionTokens=null==(s=m.usage.completion_tokens_details)?void 0:s.accepted_prediction_tokens),(null==(c=m.usage.completion_tokens_details)?void 0:c.rejected_prediction_tokens)!=null&&(S.openai.rejectedPredictionTokens=null==(d=m.usage.completion_tokens_details)?void 0:d.rejected_prediction_tokens));let h=m.choices[0];if((null==h?void 0:h.finish_reason)!=null&&(_={unified:v(h.finish_reason),raw:h.finish_reason}),(null==(p=null==h?void 0:h.logprobs)?void 0:p.content)!=null&&(S.openai.logprobs=h.logprobs.content),(null==h?void 0:h.delta)==null)return;let g=h.delta;if(null!=g.content&&(w||(n.enqueue({type:"text-start",id:"0"}),w=!0),n.enqueue({type:"text-delta",id:"0",delta:g.content})),null!=g.tool_calls)for(let e of g.tool_calls)r.processDelta(e);if(null!=g.annotations)for(let e of g.annotations)n.enqueue({type:"source",sourceType:"url",id:(0,o.generateId)(),url:e.url_citation.url,title:e.url_citation.title})},flush(e){w&&e.enqueue({type:"text-end",id:"0"}),r.flush(),e.enqueue({type:"finish",finishReason:_,usage:g(a),...null!=S?{providerMetadata:S}:{}})}})),request:{body:d},response:{headers:m}}}};function x(e){return!("error"in e)&&e.choices.some(e=>{let t=e.delta;return(null==t?void 0:t.content)!=null&&t.content.length>0||(null==t?void 0:t.tool_calls)!=null&&t.tool_calls.length>0||(null==t?void 0:t.annotations)!=null&&t.annotations.length>0})}function S(e){var t,n,r,a;if(null==e)return(0,o.createNullLanguageModelUsage)();let i=null!=(t=e.prompt_tokens)?t:0,l=null!=(n=e.completion_tokens)?n:0;return{inputTokens:{total:null!=(r=e.prompt_tokens)?r:void 0,noCache:i,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:null!=(a=e.completion_tokens)?a:void 0,text:l,reasoning:void 0},raw:e}}function k(e){switch(e){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"}}var I=(0,o.lazySchema)(()=>(0,o.zodSchema)(r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({text:r.z.string(),finish_reason:r.z.string(),logprobs:r.z.object({tokens:r.z.array(r.z.string()),token_logprobs:r.z.array(r.z.number()),top_logprobs:r.z.array(r.z.record(r.z.string(),r.z.number())).nullish()}).nullish()})),usage:r.z.object({prompt_tokens:r.z.number(),completion_tokens:r.z.number(),total_tokens:r.z.number()}).nullish()}))),T=(0,o.lazySchema)(()=>(0,o.zodSchema)(r.z.union([r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({text:r.z.string(),finish_reason:r.z.string().nullish(),index:r.z.number(),logprobs:r.z.object({tokens:r.z.array(r.z.string()),token_logprobs:r.z.array(r.z.number()),top_logprobs:r.z.array(r.z.record(r.z.string(),r.z.number())).nullish()}).nullish()})),usage:r.z.object({prompt_tokens:r.z.number(),completion_tokens:r.z.number(),total_tokens:r.z.number()}).nullish()}),i]))),C=(0,o.lazySchema)(()=>(0,o.zodSchema)(r.z.object({echo:r.z.boolean().optional(),logitBias:r.z.record(r.z.string(),r.z.number()).optional(),suffix:r.z.string().optional(),user:r.z.string().optional(),logprobs:r.z.union([r.z.boolean(),r.z.number()]).optional()}))),E=class e{constructor(e,t){this.specificationVersion="v4",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}static[n.WORKFLOW_SERIALIZE](e){return(0,o.serializeModelOptions)({modelId:e.modelId,config:e.config})}static[n.WORKFLOW_DESERIALIZE](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:l,presencePenalty:s,stopSequences:u,responseFormat:c,tools:d,toolChoice:p,seed:m,providerOptions:h}){let g=[],f={...await (0,o.parseProviderOptions)({provider:"openai",providerOptions:h,schema:C}),...await (0,o.parseProviderOptions)({provider:this.providerOptionsName,providerOptions:h,schema:C})};null!=i&&g.push({type:"unsupported",feature:"topK"}),(null==d?void 0:d.length)&&g.push({type:"unsupported",feature:"tools"}),null!=p&&g.push({type:"unsupported",feature:"toolChoice"}),null!=c&&"text"!==c.type&&g.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});let{prompt:y,stopSequences:v}=function({prompt:e,user:t="user",assistant:o="assistant"}){let n="";for(let{role:r,content:i}of("system"===e[0].role&&(n+=`${e[0].content}
|