thursday-agent 0.17.0 → 0.17.2
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 +2 -0
- package/.next/build-manifest.json +3 -3
- package/.next/prerender-manifest.json +3 -3
- package/.next/routes-manifest.json +12 -0
- package/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +1 -1
- package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/api/artifact/route.js +9 -8
- package/.next/server/app/api/artifact/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/memory/files/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/memory/route.js +8 -7
- package/.next/server/app/api/bot/memory/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/route.js +8 -7
- package/.next/server/app/api/bot/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/thread/[id]/route.js +4 -4
- package/.next/server/app/api/bot/thread/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/thread/route.js +3 -3
- package/.next/server/app/api/bot/thread/route.js.nft.json +1 -1
- package/.next/server/app/api/config/route.js.nft.json +1 -1
- package/.next/server/app/api/events/route.js.nft.json +1 -1
- package/.next/server/app/api/favicon/[host]/route.js +4 -3
- package/.next/server/app/api/favicon/[host]/route.js.nft.json +1 -1
- package/.next/server/app/api/file/[...path]/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/automatic/route/app-paths-manifest.json +3 -0
- package/.next/server/app/api/llm-model/automatic/route/build-manifest.json +12 -0
- package/.next/server/app/api/llm-model/automatic/route/server-reference-manifest.json +4 -0
- package/.next/server/app/api/llm-model/automatic/route.js +17 -0
- package/.next/server/app/api/llm-model/automatic/route.js.map +5 -0
- package/.next/server/app/api/llm-model/automatic/route.js.nft.json +1 -0
- package/.next/server/app/api/llm-model/automatic/route_client-reference-manifest.js +3 -0
- package/.next/server/app/api/llm-model/catalog/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/credits/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/subscription/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/[name]/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/oauth/callback/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/tools/route.js.nft.json +1 -1
- package/.next/server/app/api/memory/edit/route.js +14 -13
- package/.next/server/app/api/memory/edit/route.js.nft.json +1 -1
- package/.next/server/app/api/memory/route.js.nft.json +1 -1
- package/.next/server/app/api/reach/route.js +17 -16
- package/.next/server/app/api/reach/route.js.nft.json +1 -1
- package/.next/server/app/api/routine/route.js +10 -10
- package/.next/server/app/api/routine/route.js.nft.json +1 -1
- package/.next/server/app/api/signins/route.js.nft.json +1 -1
- package/.next/server/app/api/skills/[source]/[name]/route.js +9 -8
- package/.next/server/app/api/skills/[source]/[name]/route.js.nft.json +1 -1
- package/.next/server/app/api/skills/route.js +9 -8
- package/.next/server/app/api/skills/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/call/end/route/app-paths-manifest.json +3 -0
- package/.next/server/app/api/thursday/call/end/route/build-manifest.json +12 -0
- package/.next/server/app/api/thursday/call/end/route/server-reference-manifest.json +4 -0
- package/.next/server/app/api/thursday/call/end/route.js +17 -0
- package/.next/server/app/api/thursday/call/end/route.js.map +5 -0
- package/.next/server/app/api/thursday/call/end/route.js.nft.json +1 -0
- package/.next/server/app/api/thursday/call/end/route_client-reference-manifest.js +3 -0
- package/.next/server/app/api/thursday/call/route.js +6 -6
- package/.next/server/app/api/thursday/call/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/settings/route.js +5 -5
- package/.next/server/app/api/thursday/settings/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/text/route.js +16 -15
- package/.next/server/app/api/thursday/text/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/tool-call/route.js +13 -12
- package/.next/server/app/api/thursday/tool-call/route.js.nft.json +1 -1
- package/.next/server/app/api/workspace/files/route.js +5 -5
- package/.next/server/app/api/workspace/files/route.js.nft.json +1 -1
- package/.next/server/app/api/workspace/route.js +5 -5
- package/.next/server/app/api/workspace/route.js.nft.json +1 -1
- package/.next/server/app/artifact/[...path]/page/server-reference-manifest.json +3 -3
- package/.next/server/app/artifact/[...path]/page.js +2 -2
- package/.next/server/app/artifact/[...path]/page.js.nft.json +1 -1
- package/.next/server/app/artifact/[...path]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/favicon.ico/route.js.nft.json +1 -1
- package/.next/server/app/manifest.webmanifest/route.js.nft.json +1 -1
- package/.next/server/app/page/server-reference-manifest.json +60 -60
- package/.next/server/app/page.js +8 -8
- 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 +2 -0
- package/.next/server/chunks/{[externals]__178rv3v._.js → [externals]__12stas-._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__00qyw01._.js +1 -1
- package/.next/server/chunks/{[root-of-the-server]__1ignh6-._.js → [root-of-the-server]__01k3vi3._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__01ypm_z._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__021dkui._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__03vunn6._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__03xamry._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__05dp5tr._.js +1 -1
- package/.next/server/chunks/{[root-of-the-server]__208vmyf._.js → [root-of-the-server]__061o2_x._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__09gdscj._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__0bqveex._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__0eivkvk._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__0f7m79q._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0g38-aj._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__0h656y-._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__0hkxwim._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0hm3tiq._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__0hzdqnv._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__0liwkmx._.js +4 -4
- package/.next/server/chunks/[root-of-the-server]__0ljizgj._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__0mgyt8p._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__0mrk2it._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0nmust6._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__0p80i1n._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0qzho69._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0sm5xvm._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0svzjwa._.js +3 -3
- package/.next/server/chunks/{[root-of-the-server]__0b36yfw._.js → [root-of-the-server]__0ts7ai0._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__1-18_pz._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1-rmal0._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__13hng6h._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1_04mcf._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__1_h4hf9._.js +3 -3
- package/.next/server/chunks/[root-of-the-server]__1ceammd._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1ckt1yj._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1cu5f3z._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__1hviq62._.js +5 -0
- package/.next/server/chunks/{[root-of-the-server]__12m24xl._.js → [root-of-the-server]__1k2qs1m._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__1kmnkbk._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1ndi14y._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1p47fbb._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__1pugoq0._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1t02-1p._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1t0jj1j._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1vlxv19._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__1ygplx1._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1zn039k._.js +1 -1
- package/.next/server/chunks/_05gl-xy._.js +5 -5
- package/.next/server/chunks/_06hnfi8._.js +8 -0
- package/.next/server/chunks/_06u9yo-._.js +1 -1
- package/.next/server/chunks/_07nxi75._.js +25 -21
- package/.next/server/chunks/_08354bn._.js +25 -21
- package/.next/server/chunks/_08btiir._.js +3 -3
- package/.next/server/chunks/_0c49lmw._.js +5 -0
- package/.next/server/chunks/_0ey0s6v._.js +3 -0
- package/.next/server/chunks/_0hgvg55._.js +5 -0
- package/.next/server/chunks/_0j0-gq6._.js +2 -2
- package/.next/server/chunks/_0nn99o2._.js +1 -1
- package/.next/server/chunks/_0p6v1fr._.js +2 -2
- package/.next/server/chunks/_0s8ao8z._.js +3 -0
- package/.next/server/chunks/_0srlnvd._.js +1 -1
- package/.next/server/chunks/_0t_7gji._.js +1 -1
- package/.next/server/chunks/_0ucx1jv._.js +3 -0
- package/.next/server/chunks/_0uzj57i._.js +1 -1
- package/.next/server/chunks/_0xygcxs._.js +25 -21
- package/.next/server/chunks/_1-sk_q4._.js +1 -1
- package/.next/server/chunks/{_1xcnogc._.js → _108gsm8._.js} +4 -4
- package/.next/server/chunks/{_20oecmn._.js → _15negpy._.js} +4 -4
- package/.next/server/chunks/_19fh9t2._.js +3 -0
- package/.next/server/chunks/_19kea1l._.js +18 -18
- package/.next/server/chunks/_1dtm9bs._.js +1 -1
- package/.next/server/chunks/_1dxq827._.js +2 -2
- package/.next/server/chunks/_1e54wxa._.js +1 -1
- package/.next/server/chunks/_1frcwj1._.js +3 -0
- package/.next/server/chunks/_1gn2r2q._.js +5 -5
- package/.next/server/chunks/_1gxankq._.js +2 -2
- package/.next/server/chunks/_1i3uucm._.js +5 -0
- package/.next/server/chunks/_1m88lkh._.js +9 -9
- package/.next/server/chunks/_1mx9sfo._.js +1 -1
- package/.next/server/chunks/_1q6e56i._.js +5 -5
- package/.next/server/chunks/_1qxheoa._.js +1 -1
- package/.next/server/chunks/_1t5ijzv._.js +3 -0
- package/.next/server/chunks/_1wwl_7o._.js +1 -1
- package/.next/server/chunks/_1zfxb7j._.js +1 -1
- package/.next/server/chunks/_211dn2c._.js +1 -1
- package/.next/server/chunks/_next-internal_server_app_api_llm-model_automatic_route_actions_1-eyan7.js +3 -0
- package/.next/server/chunks/_next-internal_server_app_api_thursday_call_end_route_actions_0u5xjft.js +3 -0
- package/.next/server/chunks/config_ts_1g4sz5o._.js +1 -1
- package/.next/server/chunks/{features_0wm-ujw._.js → features_bot_08z387_._.js} +4 -4
- package/.next/server/chunks/{ssr/[root-of-the-server]__07660xu._.js → features_bot_0zy_q8y._.js} +8 -9
- package/.next/server/chunks/features_bot_1dfrdsb._.js +37 -0
- package/.next/server/chunks/features_workspace_workspace_ts_13h82gv._.js +3 -3
- package/.next/server/chunks/features_workspace_workspace_ts_1iyjroj._.js +3 -3
- package/.next/server/chunks/node_modules_103lpef._.js +3 -0
- package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_0_nz09c._.js → node_modules_consola_dist_chunks_prompt_mjs_0-t5tbs._.js} +1 -1
- package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_1341cnf._.js → node_modules_consola_dist_chunks_prompt_mjs_039fwo9._.js} +1 -1
- package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_1x3bsmx._.js → node_modules_consola_dist_chunks_prompt_mjs_0pce1b3._.js} +1 -1
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_0tvy5lq._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_0wxw35t._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1dlthym._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1smfi4-._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1x1omfi._.js +3 -0
- package/.next/server/chunks/node_modules_consola_dist_chunks_prompt_mjs_20is7e3._.js +3 -0
- package/.next/server/chunks/ssr/{[root-of-the-server]__149x25m._.js → [root-of-the-server]__0-af_o7._.js} +2 -2
- package/.next/server/chunks/ssr/[root-of-the-server]__09f39cp._.js +4 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0ouu4qp._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__0q9g9ea._.js +5 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__17h1ggo._.js +11 -9
- package/.next/server/chunks/ssr/[root-of-the-server]__1jyeu61._.js +1 -1
- package/.next/server/chunks/ssr/{_0aeknva._.js → _01al00i._.js} +2 -2
- package/.next/server/chunks/ssr/_088vzgn._.js +1 -1
- package/.next/server/chunks/ssr/_0afrpci._.js +1 -1
- package/.next/server/chunks/ssr/_0bgse1c._.js +162 -0
- package/.next/server/chunks/ssr/_0cd6g3l._.js +15 -15
- package/.next/server/chunks/ssr/_0cv9tmv._.js +1 -1
- package/.next/server/chunks/ssr/{_0_vnw9v._.js → _0e2fnvg._.js} +2 -2
- package/.next/server/chunks/ssr/_0fo4552._.js +25 -21
- package/.next/server/chunks/ssr/_0jstvlg._.js +39 -0
- package/.next/server/chunks/ssr/{_0r0g9ki._.js → _0l7rjg5._.js} +2 -2
- package/.next/server/chunks/ssr/_0qsmpcu._.js +1 -1
- package/.next/server/chunks/ssr/_0v9r8g2._.js +1 -1
- package/.next/server/chunks/ssr/{_18-e7zi._.js → _0vo_oym._.js} +4 -4
- package/.next/server/chunks/ssr/_0x8ophf._.js +1 -1
- package/.next/server/chunks/ssr/{_0ztbn5q._.js → _0xfafez._.js} +2 -2
- package/.next/server/chunks/ssr/_0z38nha._.js +1 -1
- package/.next/server/chunks/ssr/_10-_awu._.js +1 -1
- package/.next/server/chunks/ssr/{_1z6pirx._.js → _10_ph1t._.js} +2 -2
- package/.next/server/chunks/ssr/_116lfdc._.js +3 -0
- package/.next/server/chunks/ssr/_14dfh7a._.js +1 -1
- package/.next/server/chunks/ssr/_14oirtb._.js +3 -0
- package/.next/server/chunks/ssr/{_1umbr78._.js → _163dr78._.js} +2 -2
- package/.next/server/chunks/ssr/{_1c5iqz1._.js → _17a4qyk._.js} +3 -3
- package/.next/server/chunks/ssr/{_1sttj8x._.js → _1_5xof_._.js} +2 -2
- package/.next/server/chunks/ssr/{_1hbjh6n._.js → _1aqjk-1._.js} +2 -2
- package/.next/server/chunks/ssr/{_0n2scfq._.js → _1dfv66y._.js} +2 -2
- package/.next/server/chunks/ssr/_1neoj22._.js +1 -1
- package/.next/server/chunks/ssr/_1ou5sj0._.js +1 -1
- package/.next/server/chunks/ssr/{_15m5ctz._.js → _1tmw842._.js} +2 -2
- package/.next/server/chunks/ssr/_1uij_rj._.js +1 -1
- package/.next/server/chunks/ssr/_1w9w1ok._.js +1 -1
- package/.next/server/chunks/ssr/features_0796o8r._.js +1 -1
- package/.next/server/chunks/ssr/features_bot_0ouemw8._.js +3 -0
- package/.next/server/chunks/ssr/{features_133mpna._.js → features_bot_0tb4ui-._.js} +2 -2
- package/.next/server/chunks/ssr/{features_config_0n0zu89._.js → features_config_09n-q9q._.js} +3 -3
- package/.next/server/chunks/ssr/features_connectors_components_mcp-setting_tsx_0jmbgvp._.js +1 -1
- package/.next/server/chunks/ssr/features_memory_components_memory-setting_tsx_0oa43sw._.js +1 -1
- package/.next/server/chunks/ssr/features_routine_components_routine-setting_tsx_055fknz._.js +1 -1
- package/.next/server/chunks/ssr/features_workspace_workspace_ts_1wc7_u_._.js +4 -4
- package/.next/server/chunks/ssr/{node_modules_1hefp6h._.js → node_modules_021lid9._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0kwie-o._.js → node_modules_04x5wyv._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_180l3i0._.js → node_modules_096up6a._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_00h1t1j._.js → node_modules_0__0tvm._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_03uejh6._.js → node_modules_0cjnmzp._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1ubln7w._.js → node_modules_0d6j33x._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1_n9o9s._.js → node_modules_0gd9hbz._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0zf3wuu._.js → node_modules_0k8-y89._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0u_8z64._.js → node_modules_0m73b88._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_09ikzel._.js → node_modules_0msrhxf._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0f5bmkb._.js → node_modules_0nmkv-v._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_07mo9rn._.js → node_modules_0nw5jz7._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_09e8kz_._.js → node_modules_0q-klni._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_02ficyi._.js → node_modules_10_fv2a._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_142z3o5._.js → node_modules_113l3e5._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1wyhtw9._.js → node_modules_13bqv6i._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0_d_7gq._.js → node_modules_13g-d25._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0r-9e4n._.js → node_modules_156kv_t._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_06grs09._.js → node_modules_1_8-jcj._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1fw32pg._.js → node_modules_1gq3ght._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0_p8w7p._.js → node_modules_1k5i-_9._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_03q71_j._.js → node_modules_1lmyts8._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1irot3r._.js → node_modules_1p_6sq7._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1om2itc._.js → node_modules_1qstb1x._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_197vh1s._.js → node_modules_1ri_eip._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1-7fc7h._.js → node_modules_1xb-ndg._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0aczkbn._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0amkw0b._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0ah684s._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0zq3l45._.js} +1 -1
- package/.next/server/middleware-build-manifest.js +3 -3
- package/.next/server/middleware.js +1 -1
- 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 +61 -61
- package/.next/static/chunks/{38edd4rpcbvzp.js → 01l7kw74vfp32.js} +1 -1
- package/.next/static/chunks/0a5_-jqhaktjj.js +1 -0
- package/.next/static/chunks/{0_b_bi2pobasx.js → 0obogzscwwekj.js} +2 -2
- package/.next/static/chunks/{1-63yde5eaz7i.js → 0p2f6uv4xytfm.js} +1 -1
- package/.next/static/chunks/{2v6e_9p95o2e3.js → 0uxq_vs6uxi-b.js} +1 -1
- package/.next/static/chunks/{024plctckvq-1.js → 166smhw8v-s3j.js} +1 -1
- package/.next/static/chunks/{1wbqaidq7vc3_.js → 1bnhw-5fj7aiz.js} +1 -1
- package/.next/static/chunks/1cglo3a2mbeou.js +1 -0
- package/.next/static/chunks/{0sv142q1yrva2.js → 1in6nxpu33iab.js} +1 -1
- package/.next/static/chunks/1u7kg91f9qy3g.js +1 -0
- package/.next/static/chunks/{0sowxe4nnl5qu.js → 1xv4g10m-cl1s.js} +1 -1
- package/.next/static/chunks/{0dfvwgnyrp8qt.js → 2ajs12-fcdwzm.js} +1 -1
- package/.next/static/chunks/2i7qtmxc1kuqg.js +1 -0
- package/.next/static/chunks/{3-qp777vtfglj.js → 2kz1f6r59nky0.js} +1 -1
- package/.next/static/chunks/2qgkbdshzpq1c.js +1 -0
- package/.next/static/chunks/{1bgvxd3xny53w.js → 2zbl41hed17g3.js} +2 -2
- package/.next/static/chunks/35jj-5u4te56r.js +1 -0
- package/.next/static/chunks/37ixzapa06xlo.js +1 -0
- package/.next/static/chunks/3b96xy59nl_gd.js +1 -0
- package/.next/static/chunks/{0f47nnshdlucs.js → 3gsxnqqqphh-1.js} +1 -1
- package/.next/static/chunks/{44vre0f7xqsh-.js → 3jtcieuk1l6tw.js} +1 -1
- package/.next/static/chunks/{05scfrgo_a_5_.js → 3k1d8y03t5nax.js} +1 -1
- package/.next/static/chunks/3sla-dm1puqd1.js +35 -0
- package/.next/static/chunks/3t2c76awm9k_p.js +1 -0
- package/.next/static/chunks/3vrmcm31ih7gb.js +1 -0
- package/.next/static/chunks/3yiqr95d7ybeq.js +15 -0
- package/bin/autostart.mjs +4 -1
- package/bin/database.mjs +26 -4
- package/bin/lock.mjs +59 -0
- package/bin/node-check.mjs +21 -0
- package/bin/thursday.mjs +8 -1
- package/guide/bots.md +4 -2
- package/guide/calls.md +11 -9
- package/guide/memory.md +3 -2
- package/guide/phone.md +7 -4
- package/guide/setup.md +26 -9
- package/guide/trouble.md +11 -4
- package/package.json +1 -1
- package/public/voices/intro/asleepBare-15199d56.ogg +0 -0
- package/public/voices/intro/style-88adf274.ogg +0 -0
- package/seed-skills/concierge/travel/scripts/itinerary.mjs +6 -4
- package/skills/artifact/references/book.md +2 -1
- package/skills/artifact/references/sheet.md +12 -7
- package/skills/artifact/runtime/sheet/format.mjs +16 -9
- package/skills/artifact/scripts/book.mjs +19 -6
- package/skills/artifact/scripts/spreadsheet.mjs +194 -97
- package/skills/browser/SKILL.md +9 -6
- package/.next/server/chunks/[root-of-the-server]__03b09q0._.js +0 -5
- package/.next/server/chunks/[root-of-the-server]__05n-hql._.js +0 -5
- package/.next/server/chunks/[root-of-the-server]__0j_nz36._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0jzwdg-._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0tsded0._.js +0 -5
- package/.next/server/chunks/[root-of-the-server]__12tahb4._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1de1o6m._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1yl5l25._.js +0 -3
- package/.next/server/chunks/_02lipqs._.js +0 -5
- package/.next/server/chunks/_05sa7xl._.js +0 -3
- package/.next/server/chunks/_074f2ts._.js +0 -3
- package/.next/server/chunks/_0caua_s._.js +0 -3
- package/.next/server/chunks/_0p-h6xe._.js +0 -5
- package/.next/server/chunks/_0up2a9o._.js +0 -3
- package/.next/server/chunks/_17i1lt2._.js +0 -3
- package/.next/server/chunks/_1hy9x9_._.js +0 -3
- package/.next/server/chunks/_1hyvcgk._.js +0 -5
- package/.next/server/chunks/_1wl2g8_._.js +0 -6
- package/.next/server/chunks/_1y3mnz4._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__10eb-1x._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__19s8qyj._.js +0 -3
- package/.next/server/chunks/ssr/_0o_o9ji._.js +0 -3
- package/.next/server/chunks/ssr/_0qne8xs._.js +0 -3
- package/.next/server/chunks/ssr/_0rvbegp._.js +0 -7
- package/.next/server/chunks/ssr/_1vtgiou._.js +0 -162
- package/.next/server/chunks/ssr/features_bot_1kr0_m-._.js +0 -3
- package/.next/static/chunks/04toe_3nqfjqt.js +0 -1
- package/.next/static/chunks/0mtfu8adz57qz.js +0 -1
- package/.next/static/chunks/0tp868040z9nn.js +0 -35
- package/.next/static/chunks/14qitm0kwsb6g.js +0 -15
- package/.next/static/chunks/1cyrrz4q871aj.js +0 -1
- package/.next/static/chunks/1st3b0c9vhxg3.js +0 -1
- package/.next/static/chunks/28sxb_k460e9h.js +0 -1
- package/.next/static/chunks/33ekkscpcq-z1.js +0 -1
- package/.next/static/chunks/388l-zszwa_jf.js +0 -1
- package/.next/static/chunks/3bwrvpjk95_x4.js +0 -1
- package/.next/static/chunks/3itdg6t243u6f.js +0 -1
- package/.next/static/chunks/3kj0pri2oc1g1.js +0 -1
- package/public/voices/intro/style-cb6fa4f7.ogg +0 -0
- /package/.next/static/{VtbCMn-0G969p8QJsWdGv → 8I2hKtciyA9LXvd8txuOz}/_buildManifest.js +0 -0
- /package/.next/static/{VtbCMn-0G969p8QJsWdGv → 8I2hKtciyA9LXvd8txuOz}/_clientMiddlewareManifest.js +0 -0
- /package/.next/static/{VtbCMn-0G969p8QJsWdGv → 8I2hKtciyA9LXvd8txuOz}/_ssgManifest.js +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
module.exports=[652619,a=>a.a(async(b,c)=>{try{var d=a.i(666680),e=a.i(347299),f=a.i(345364),g=a.i(47919),h=a.i(868468),i=a.i(53112),j=a.i(569572),k=a.i(725466),l=a.i(176668),m=a.i(523095),n=a.i(293480),o=a.i(8412),p=a.i(182248),q=a.i(689656),r=b([k]);[k]=r.then?(await r)():r;let B="app_EMoamEEZ73f0CkXaXp7hrann",C="http://localhost:1455/auth/callback",D=["127.0.0.1","::1"],E="thursday",{apiKeyName:F,label:G}=q.TEXT_MODEL_PROVIDERS.chatgpt,H=`${G} is not signed in — sign in from Config.`,I=i.z.object({access:i.z.string().min(1),refresh:i.z.string().min(1),expires:i.z.number(),accountId:i.z.string().min(1),plan:i.z.string().nullable()}),J=globalThis,K=J.__chatgptRenewal??=(0,o.createKeyedLock)();async function s(){t();let a=(0,d.randomBytes)(32).toString("base64url"),b=(0,d.randomBytes)(16).toString("hex"),c=[],f=(d,e)=>{u(d.url??"/",{state:b,verifier:a}).then(a=>{e.writeHead(a.status,{"content-type":"text/html; charset=utf-8"}),e.end((0,m.oauthPage)(a.title,a.detail,{autoClose:200===a.status}),()=>{a.last&&J.__chatgptListeners===c&&t()})})};for(let a of D){let b=(0,e.createServer)(f),d=await new Promise(c=>{b.once("error",c),b.listen(1455,a,()=>c(null))});if(!d){c.push(b);continue}if("EADDRNOTAVAIL"!==d.code&&"EAFNOSUPPORT"!==d.code){for(let a of c)a.close();(0,n.publicError)("EADDRINUSE"===d.code?"Port 1455 is in use by another app — often a ChatGPT or Codex sign-in still waiting. Finish or close it, then try again.":`Could not wait for the sign-in: ${(0,p.errorToString)(d)}`)}}J.__chatgptListeners=c,setTimeout(()=>{J.__chatgptListeners===c&&t()},j.CHATGPT_SIGN_IN.waitMs).unref();let g=new URL("https://auth.openai.com/oauth/authorize");return g.search=new URLSearchParams({response_type:"code",client_id:B,redirect_uri:C,scope:"openid profile email offline_access",code_challenge:(0,d.createHash)("sha256").update(a).digest("base64url"),code_challenge_method:"S256",state:b,id_token_add_organizations:"true",codex_cli_simplified_flow:"true",originator:E}).toString(),g.toString()}function t(){let a=J.__chatgptListeners;for(let b of(J.__chatgptListeners=null,a??[]))b.close(),b.closeIdleConnections()}async function u(a,b){let c=new URL(a,C);if("/auth/callback"!==c.pathname)return{status:404,title:"Not found",detail:"",last:!1};let d=c.searchParams.get("error");if(d){let a=c.searchParams.get("error_description");return{status:400,title:"Sign-in failed",detail:a?`${d}: ${a}`:d,last:!0}}let e=c.searchParams.get("code");if(!e||c.searchParams.get("state")!==b.state)return{status:400,title:"Sign-in failed",detail:"This is not the sign-in that was started. Start again from Config.",last:!1};try{let a=await v({grant_type:"authorization_code",code:e,code_verifier:b.verifier,redirect_uri:C});return await (0,k.writeConfig)(F,JSON.stringify(a)),{status:200,title:"Signed in to ChatGPT",detail:"Bots can run on your plan now. This window closes itself.",last:!0}}catch(a){return l.logger.warn({cause:a},"chatgpt sign-in failed"),{status:502,title:"Sign-in failed",detail:(0,p.errorToString)(a),last:!0}}}async function v(a){let b=await fetch("https://auth.openai.com/oauth/token",{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:B,...a})}).catch(a=>{l.logger.warn({cause:a},"chatgpt token endpoint unreachable"),(0,n.publicError)("Could not reach ChatGPT's sign-in")}),c=await b.json().catch(()=>null),d=c?.access_token;if(!b.ok||!d){let a=c?.error,d="string"==typeof a?[a,c?.error_description].filter(Boolean).join(": "):a?.message??a?.code??"";(0,n.publicError)(`ChatGPT's sign-in answered ${b.status}${d?`: ${d}`:""}`)}let e=function(a){try{let b=JSON.parse(Buffer.from(a.split(".")[1]??"","base64url").toString("utf8")),c=b["https://api.openai.com/auth"]??{};return{accountId:"string"==typeof c.chatgpt_account_id?c.chatgpt_account_id:null,plan:"string"==typeof c.chatgpt_plan_type?c.chatgpt_plan_type:null,expires:"number"==typeof b.exp?1e3*b.exp:null}}catch{return{accountId:null,plan:null,expires:null}}}(d),f=c?.refresh_token??a.refresh_token;e.accountId&&f||(0,n.publicError)("ChatGPT's sign-in came back without an account");let g=c?.expires_in;return{access:d,refresh:f,expires:"number"==typeof g?Date.now()+1e3*g:e.expires??Date.now(),accountId:e.accountId,plan:e.plan}}async function w(){let a=await (0,k.readConfig)(F);if(!a)return null;try{return I.parse(JSON.parse(a))}catch{return null}}let L=a=>a.expires-j.CHATGPT_SIGN_IN.renewBeforeMs<=Date.now();async function x(){let a=await w();return(a||(0,n.publicError)(H),L(a))?K(F,async()=>{let a=await w();if(a||(0,n.publicError)(H),!L(a))return a;try{let b=await v({grant_type:"refresh_token",refresh_token:a.refresh});return await (0,k.writeConfig)(F,JSON.stringify(b)),b}catch(a){(0,n.publicError)(`Could not renew the ${G} sign-in (${(0,p.errorToString)(a)}). If it keeps failing, sign in again from Config.`)}}):a}async function y(a,b){let c=await x(),d=new Headers(b?.headers);if(d.set("authorization",`Bearer ${c.access}`),d.set("chatgpt-account-id",c.accountId),d.set("originator",E),b?.method!=="POST"||"string"!=typeof b.body||!String(a).endsWith("/responses"))return fetch(a,{...b,headers:d});let e=JSON.parse(b.body),f=!0===e.stream,g=[];e.input=(e.input??[]).filter(a=>"system"!==a.role&&"developer"!==a.role||(g.push("string"==typeof a.content?a.content:(a.content??[]).map(a=>a.text??"").join("\n")),!1)),e.instructions=[e.instructions,...g].filter(Boolean).join("\n\n")||"You are a helpful assistant.",e.store=!1,e.stream=!0,e.max_output_tokens=void 0,d.set("accept","text/event-stream");let h=await fetch(a,{...b,headers:d,body:JSON.stringify(e)});return 429===h.status?z(h):f||!h.ok?h:A(h)}async function z(a){let b=await a.text(),c={};try{c=JSON.parse(b).error??{}}catch{}if(!/usage_limit_reached|usage_not_included/.test(`${c.code} ${c.type}`)){let c=a.headers.get("retry-after");return new Response(b,{status:429,headers:{"content-type":"application/json",...c?{"retry-after":c}:{}}})}let d=c.resets_at?1e3*c.resets_at:c.resets_in_seconds?Date.now()+1e3*c.resets_in_seconds:null,e=c.plan_type?` on the ${c.plan_type} plan`:"",f=d?` It resets in ${(0,h.formatDistanceToNowStrict)(d)}.`:"";return Response.json({error:{message:`${G} usage limit reached${e}.${f}`,code:c.code??c.type}},{status:402})}async function A(a){let b=[],c=null,d=null;for(let e of(await a.text()).replaceAll("\r\n","\n").split("\n\n")){let a,f=e.split("\n").filter(a=>a.startsWith("data:")).map(a=>a.slice(5).trimStart()).join("\n");if(f&&"[DONE]"!==f){try{a=JSON.parse(f)}catch{continue}"response.output_item.done"===a.type?b.push(a.item):"response.completed"===a.type||"response.incomplete"===a.type?c=a.response??{}:"response.failed"===a.type?d=a.response?.error??{message:"The response failed"}:"error"===a.type&&(d={code:a.code,message:a.message})}}return d||!c?Response.json({error:{message:d?.message??"The stream ended before the response finished",code:d?.code}},{status:d?.code==="context_length_exceeded"?400:500}):Response.json({...c,output:c.output?.length?c.output:b})}a.s(["chatGptModel",0,function(a){let b=(0,f.createOpenAI)({baseURL:"https://chatgpt.com/backend-api/codex",apiKey:"signed-in",headers:{"OpenAI-Beta":"responses=experimental"},fetch:y}),c=(0,d.randomUUID)();return(0,g.wrapLanguageModel)({model:b.responses(a),middleware:{transformParams:async({params:a})=>({...a,providerOptions:{...a.providerOptions,openai:{promptCacheKey:c,...a.providerOptions?.openai,store:!1}}})}})},"startChatGptSignIn",0,s]),c()}catch(a){c(a)}},!1),884780,a=>{"use strict";a.i(902157),a.i(912714);var b=a.i(750227),c=a.i(569572);(0,b.join)(c.APP_DIR,"guide");let d=".guide";a.s(["botGuideLine",0,()=>`How ${c.APP_NAME} itself works for the user — its screens and settings — is written under \`${d}/\` here, \`index.md\` first; read it only when the job is about the app.`,"guideLine",0,()=>`How ${c.APP_NAME} works for the person using it — its screens, its settings, what it connects to, what to do when something stops — is written under \`${d}/\` here, \`index.md\` first. Read it whenever an answer depends on how the app works: what can be asked for, where something is changed, a wish that needs a setting switched on, something that stopped or was refused. Answer from it rather than from what you assume.`])},738131,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(868468),f=a.i(569572),g=a.i(875931),h=a.i(938934),i=a.i(978876),j=a.i(375827),k=a.i(127507),l=a.i(467650),m=a.i(138902),n=a.i(345846),o=a.i(617594),p=a.i(622547),q=a.i(128232),r=a.i(382442),s=a.i(451017),t=a.i(762008),u=a.i(547613),v=a.i(446957),w=a.i(138100),x=a.i(821415),y=a.i(706210),z=a.i(176668),A=a.i(293480),B=a.i(987674),C=a.i(182248),D=b([g,i,m,n,o,p,q,s,w]);async function E(b){let{listThreadOverview:c}=await a.A(343064),d=await c();if(!d.length)return"No thread has been started yet.";let e=d.map(a=>`"${a.label}" (${a.bot}, ${a.status})`).join(", ");return`There is no thread called "${b}". The latest are: ${e}. Call again with one of those labels.`}async function F(a,b){let c=[];for(let[a,e]of Object.entries(b)){let b=await (0,d.asSchema)(e.inputSchema).jsonSchema,f="string"==typeof e.description?e.description:"";c.push({name:a,tokens:(0,B.estimateTokens)(f)+(0,B.estimateTokens)(JSON.stringify(b))})}c.sort((a,b)=>b.tokens-a.tokens);let e=c.reduce((a,b)=>a+b.tokens,0);z.logger.debug(`${a} tools ${e} tokens over ${c.length} — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`)}async function G(a){let b=await H(a);return f.IS_DEV&&await F(a.target,b),b}async function H(b){if("memory-edit"===b.target)return(0,n.createMemoryTools)("user",null,{countReads:!1});let c=(0,n.createMemoryTools)("call","thursday"===b.target?b.callId??null:null),z=await (0,x.openWorkspace)();if("thursday"===b.target){var B;let k,m,n=b.readSkills?(0,s.createSkillTools)({sandbox:z,skills:await (0,w.loadSkills)(z)}):{},q=!!(b.written&&b.model&&(0,g.seesToolImages)(b.model));return{...c,...n,...(0,u.createWorkspaceTools)(z,{write:!1,timeoutMs:f.CALL_EXEC_TIMEOUT_MS}),...!1===b.webSearch?{}:await (0,p.createCallSearchTool)(z),...Object.fromEntries(Object.entries((B=b.callId,k=async b=>{let{resolveThread:c}=await a.A(343064);return(b.trim()?await c(b.trim()):null)??await E(b)},m=async(b,c,d)=>{let e=await a.A(763543);try{return await e.answerThread(b,c,"thursday",d)}catch(a){if((0,A.isPublicError)(a))return a.message;throw a}},{[t.TOOL_NAMES.thread_start]:(0,d.tool)({description:i.threadStartSpec.description,inputSchema:i.threadStartSpec.parameters,execute:async({bot:b,request:c,label:d})=>{let{findJobBot:e,listJobBots:f}=await a.A(276307),g=await e(b);if(!g||g.disabled){let a=(await f()).map(a=>a.name);return`There is no bot called "${b}". The bots are: ${a.join(", ")}. Nothing was started — call again with one of those.`}let{startThread:h}=await a.A(763543);return{threadId:await h({bot:g.name,request:c,label:d,callId:B,from:"thursday"}),note:`${g.name} has "${d}". Its updates reach the conversation on their own. Anything further about this work — a correction, the next step once it finishes — is \`${t.TOOL_NAMES.thread_tell}\` with "${d}"; a question it asks is answered with \`${t.TOOL_NAMES.thread_answer}\`.`}}}),[t.TOOL_NAMES.thread_tell]:(0,d.tool)({description:i.threadTellSpec.description,inputSchema:i.threadTellSpec.parameters,execute:async({thread:a,words:b})=>{let c=await k(a);if("string"==typeof c)return c;if(!b.trim())return"Say what to pass on.";let d=await m(c.id,b.trim());return"string"==typeof d?d:d?.answered?{label:c.label,answered:d.answered,note:`${d.answered.bot} was waiting on a question, and took this as its answer.`}:{label:c.label,bot:d?.to??c.bot,status:"running",note:"running"===c.status?"The bot reads it before its next step.":"The bot picks the thread back up from there."}}}),[t.TOOL_NAMES.thread_answer]:(0,d.tool)({description:i.threadAnswerSpec.description,inputSchema:i.threadAnswerSpec.parameters,execute:async({thread:b,bot:c,answer:d})=>{let e=await k(b);if("string"==typeof e)return e;if(!d.trim())return"Say what the answer is.";let{findThreadView:f}=await a.A(343064),g=(await f(e.id))?.room.questions??[],h=g.find(a=>a.bot.toLowerCase()===c.trim().toLowerCase());if(!h)return g.length?`${c} is not asking anything in "${e.label}". Waiting there: ${g.map(a=>a.bot).join(", ")}. Call again with that bot.`:`No question is waiting in "${e.label}". To say something else to it, use \`${t.TOOL_NAMES.thread_tell}\`.`;let i=await m(e.id,d.trim(),h.bot);return"string"==typeof i?i:{label:e.label,answered:i?.answered??{bot:h.bot,question:h.text},note:`${h.bot} has the answer to its question and goes on from it.`}}}),[t.TOOL_NAMES.thread_status]:(0,d.tool)({description:i.threadStatusSpec.description,inputSchema:i.threadStatusSpec.parameters,execute:async({thread:b})=>{let{listThreadOverview:c,findThreadView:d}=await a.A(343064),g={now:(0,h.clockNow)()},i=a=>(0,e.formatDistanceToNowStrict)((0,y.toDate)(a),{addSuffix:!0});if(!(!b.trim()||"all"===b.trim().toLowerCase())){let a=await k(b);if("string"==typeof a)return a;let c=(await d(a.id))?.room;return{...g,label:a.label,id:a.id,bot:a.bot,participants:c?.participants??[],questions:c?.questions??[],status:a.status,since:i(a.updatedAt),outcome:a.outcome,..."waiting"===a.status&&a.pending?.options.length?{options:a.pending.options}:{}}}let j=await c();return j.length?{...g,threads:j.map(a=>({id:a.id,label:a.label,bot:a.bot,status:a.status,participants:a.room.participants,questions:a.room.questions.map(a=>({...a,text:(0,C.clip)(a.text,f.PROMPT_LINE.threadStatus)})),since:i(a.updatedAt),...a.ask?{asking:a.ask.question,options:a.ask.options}:{},..."running"===a.status?{now:(0,v.threadActivity)(a.lines)}:{},...a.outcome&&"waiting"!==a.status?{outcome:(0,C.clip)(a.outcome,f.PROMPT_LINE.threadStatus)}:{}}))}:"No thread has been started yet."}}),[t.TOOL_NAMES.thread_cancel]:(0,d.tool)({description:i.threadCancelSpec.description,inputSchema:i.threadCancelSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{cancelThread:d}=await a.A(763543);return await d(c.id),{label:c.label,status:"cancelled"}}}),[t.TOOL_NAMES.thread_show]:(0,d.tool)({description:i.threadShowSpec.description,inputSchema:i.threadShowSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{appEvents:d}=await a.A(133300),{filesOnDisk:e}=await a.A(122690),{leadFirst:f,pathsIn:g,viewKindOf:h}=await a.A(394298),i=(await e(g(c.outcome??""),null)).filter(a=>"none"!==h(a));if(!i.length)return d.emit({type:"showThread",threadId:c.id}),{label:c.label,showing:"the thread"};let j=f(i);d.emit({type:"showFile",paths:j});let{markSeen:l}=await a.A(343064);return await l([c.id]),{label:c.label,showing:j[0]}}}),[t.TOOL_NAMES.thread_seen]:(0,d.tool)({description:i.threadSeenSpec.description,inputSchema:i.threadSeenSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{markSeen:d}=await a.A(343064);return await d([c.id]),{label:c.label,seen:!0}}})})).filter(([a])=>!(b.phone&&a===t.TOOL_NAMES.thread_show))),...(0,o.createRoutineTools)(),...q?(0,l.createLookTool)():{},...b.written?{}:(0,j.callTools)()}}let D=await (0,w.loadSkills)(z,b.bot),F={...(0,x.jobShellEnv)(b.session),...(0,x.botShellEnv)(b.bot,(await (await a.A(276307)).findJobBot(b.bot))?.icon)},G=!!(b.model&&(0,g.seesToolImages)(b.model.ref));return{[t.TOOL_NAMES.memory_recall]:c[t.TOOL_NAMES.memory_recall],...await (0,p.createSearchTool)(b.model,z),...(0,u.createWorkspaceTools)(z,{write:!0,env:F,guide:!0,bot:b.bot}),...await (0,m.createMcpTools)(b.bot,z),...(0,s.createSkillTools)({sandbox:z,skills:D,bot:b.bot}),...await (0,q.createSelfTools)(b.bot),...(0,k.createDeckTools)(z,b.bot,F,G),...G?(0,l.createLookTool)():{},...(0,r.createSignInTools)(z,b.bot,(0,x.jobShellEnv)(b.session)),...await (0,i.createThreadRecallTool)(b.bot,b.thread??null)}}[g,i,m,n,o,p,q,s,w]=D.then?(await D)():D,a.s(["loadTools",0,G]),c()}catch(a){c(a)}},!1),875931,a=>a.a(async(b,c)=>{try{var d=a.i(938537),e=a.i(674861),f=a.i(606016),g=a.i(388319),h=a.i(538177),i=a.i(767071),j=a.i(140358),k=a.i(873739),l=a.i(899042),m=a.i(345364),n=a.i(434451),o=a.i(655819),p=a.i(652685),q=a.i(156956),r=a.i(47919),s=a.i(569572),t=a.i(688034),u=a.i(725466),v=a.i(176668),w=a.i(293480),x=a.i(182248),y=a.i(652619),z=a.i(689656),A=b([u,y]);[u,y]=A.then?(await A)():A;let N=/context[ _-]?(length|window)|maximum context|prompt is too long|too many (input )?tokens|input token count|exceeds? the (maximum|model'?s?) (context|input|prompt|number of tokens)|maximum prompt length|request (entity )?too large/i;function B(a){return C(a).some(a=>{let{statusCode:b,message:c,error:d}=a;if(void 0!==b&&400!==b&&413!==b)return!1;let e=p.APICallError.isInstance(a)?a.responseBody:null;return[c,d,e].some(a=>"string"==typeof a&&N.test(a))})}let O=new Set([408,409,429]);function C(a){let b=[],c=[a];for(;c.length&&b.length<12;){let a=c.shift();!("object"!=typeof a||null===a||b.includes(a))&&(b.push(a),r.RetryError.isInstance(a)&&c.push(...a.errors),"cause"in a&&c.push(a.cause))}return b}let P=(a,b)=>({ref:a,model:b,searchTools:null}),Q=null;function D(a){if(null==a||""===a)return null;let b=Number(a);return Number.isFinite(b)?Math.round(1e6*b*1e4)/1e4:null}async function E(){if(Q&&Date.now()-Q.at<s.GATEWAY_CATALOG_MS)return Q.models;let a=await fetch("https://ai-gateway.vercel.sh/v1/models",{headers:{accept:"application/json"}}).catch(a=>{v.logger.warn({cause:a},"gateway catalog unreachable"),(0,w.publicError)("Could not reach the gateway")});a.ok||(0,w.publicError)(`The gateway answered ${a.status}`);let b=((await a.json()).data??[]).filter(a=>!!a.id).map(a=>{let b,c;return{id:a.id,label:a.name||a.id,owner:a.owned_by||a.id.slice(0,a.id.indexOf("/")),type:a.type??null,tags:a.tags??[],price:function(a){let b=a.pricing??{},c=D(b.input),d=D(b.output);if((a.tags??[]).includes("free")||0===c)return{in:0,out:0,note:null,free:!0};let e=b.transcription_duration_cost_per_second??b.realtime_session_duration_cost_per_second;if(e)return{in:null,out:null,note:`$${e}/s`,free:!1};if(b.speech_input_character_cost)return{in:null,out:null,note:"per character",free:!1};let f=Array.isArray(b.video_duration_pricing)?b.video_duration_pricing[0]:null;if(f?.cost_per_second)return{in:null,out:null,note:`$${f.cost_per_second}/s ${f.resolution??""}`.trimEnd(),free:!1};let g=b.image?`$${b.image}/image`:b.image_dimension_quality_pricing?"per image, by size":null;return null===c&&null===d?{in:null,out:null,note:g,free:!1}:{in:c,out:d,note:b.input_tiers?"tiered":b.varies_by_provider?"varies":g&&"+ per image",free:!1}}(a),retiring:!!a.deprecated_at,contextWindow:"number"==typeof a.context_window&&a.context_window>0?a.context_window:null,efforts:(b=(a.reasoning_options??[]).find(a=>a?.type==="effort"),(c=z.EFFORTS.filter(a=>b?.values?.includes(a))).length?c:null)}}).sort((a,b)=>a.id.localeCompare(b.id));return Q={at:Date.now(),models:b},b}async function F(a,b){if(b&&b>0)return b;let c=await G(a);return(0,z.compactAtFor)((0,z.contextWindowOf)(a.provider,a.model,c))}async function G(a){return"vercel-ai-gateway"!==a.provider?[]:await E().catch(()=>[])}async function H(a,b){let c=b??z.effortSchema.safeParse(await (0,u.readConfig)(t.DEFAULT_EFFORT_KEY)).data;if(!c)return;let d=await G(a);return(0,z.effortsOf)(a.provider,a.model,d)?.includes(c)?c:void 0}async function I(){return await E().then(a=>new Set(a.map(a=>a.id))).catch(()=>null)}async function J(a,b){if("vercel-ai-gateway"!==a)return b;let c=await I();if(!c)return b;let d=b.filter(a=>c.has(a.id));return d.length>0?d:b}async function K(a){let{label:b,apiKeyName:c,signIn:p}=z.TEXT_MODEL_PROVIDERS[a.provider],r=await (0,u.readConfig)(c);return r||(0,w.publicError)(p?`${b} is not signed in — sign in from Config.`:`No ${b} key — add one in Config.`),function(a,b){switch(a.provider){case"openai":{let c=(0,m.createOpenAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"chatgpt":return{ref:a,model:(0,y.chatGptModel)(a.model),searchTools:null};case"anthropic":{let c=(0,d.createAnthropic)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch_20260209()}}}case"google":{let c=(0,j.createGoogleGenerativeAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.googleSearch({})}}}case"xai":{let c=(0,o.createXai)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"mistral":return P(a,(0,l.createMistral)({apiKey:b})(a.model));case"deepseek":return P(a,(0,h.createDeepSeek)({apiKey:b})(a.model));case"groq":return P(a,(0,k.createGroq)({apiKey:b})(a.model));case"cerebras":return P(a,(0,e.createCerebras)({apiKey:b})(a.model));case"togetherai":return P(a,(0,n.createTogetherAI)({apiKey:b})(a.model));case"fireworks":return P(a,(0,i.createFireworks)({apiKey:b})(a.model));case"deepinfra":return P(a,(0,g.createDeepInfra)({apiKey:b})(a.model));case"cohere":return P(a,(0,f.createCohere)({apiKey:b})(a.model));case"vercel-ai-gateway":{let c=(0,q.createGateway)({apiKey:b});return{ref:a,model:c(a.model),searchTools:null}}default:(0,w.publicError)(`Not supported provider: ${String(a.provider)}`)}}(a,r)}async function L(a){let b=async a=>(0,z.defaultModelOf)({suggestModels:await J(a.id,a.suggestModels)}),c=a?z.TEXT_MODEL_PROVIDER_LIST.find(b=>b.id===a):void 0,d=["openai","xai"].map(a=>({...z.TEXT_MODEL_PROVIDERS[a],id:a}));if(c){let a=await b(c);if(a)return{provider:c.id,model:a}}let e=(0,z.parseTextModel)(await (0,u.readConfig)(t.DEFAULT_MODEL_KEY)??void 0);if(e&&await (0,u.readConfig)(z.TEXT_MODEL_PROVIDERS[e.provider].apiKeyName))return e;for(let a of[...d,...z.TEXT_MODEL_PROVIDER_LIST]){if(!await (0,u.readConfig)(a.apiKeyName))continue;let c=await b(a);if(c)return v.logger.info(`no model set, falling back to ${a.id}/${c}`),{provider:a.id,model:c}}(0,w.publicError)("No model key is set — add one in Config")}async function M(a){let b=(0,z.parseMediaModel)(await (0,u.readConfig)(t.MEDIA_MODEL_KEYS[a]));if(!b||!(0,z.canMakeKind)(b.provider,a))return null;let c=await (0,u.readConfig)(z.MEDIA_MODEL_PROVIDERS[b.provider].apiKeyName);return c?{ref:b,apiKey:c}:null}a.s(["buildImageModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).image(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).image(a.model);case"xai":return(0,o.createXai)({apiKey:b}).image(a.model);case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).image(a.model);default:(0,w.publicError)(`Not supported image provider: ${String(a.provider)}`)}},"buildSpeechModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).speech(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).speech(a.model);case"xai":return(0,o.createXai)({apiKey:b}).speech();case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).speech(a.model);default:(0,w.publicError)(`Not supported speech provider: ${String(a.provider)}`)}},"buildTranscriptionModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).transcription(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).transcription(a.model);case"xai":return(0,o.createXai)({apiKey:b}).transcription();case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).transcription(a.model);default:(0,w.publicError)(`Not supported transcription provider: ${String(a.provider)}`)}},"buildVideoModel",0,function(a,b){switch(a.provider){case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).video(a.model);case"xai":return(0,o.createXai)({apiKey:b}).video(a.model);case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).video(a.model);default:(0,w.publicError)(`${a.provider} has no video model`)}},"compactBudget",0,F,"getTextModel",0,K,"isContextOverflow",0,B,"isProviderRefusal",0,function(a){return!B(a)&&C(a).some(a=>{let{statusCode:b}=a;return"number"==typeof b&&b>=400&&b<500&&!O.has(b)})},"modelErrorToString",0,function(a){if(!p.APICallError.isInstance(a))return(0,x.errorToString)(a);let b=a.statusCode?` (${a.statusCode})`:"",c=a.responseBody?.trim(),d=c&&!c.includes(a.message)?` ${(0,x.clip)(c,300)}`:"";return`${a.message}${b}${d}`},"resolveDefaultModel",0,L,"resolveMediaRef",0,M,"runEffort",0,H,"seesToolImages",0,function(a){let b="vercel-ai-gateway"===a.provider?z.GATEWAY_OWNERS[a.model.split("/")[0]]:a.provider;return void 0!==b&&["openai","chatgpt","anthropic","google","xai"].includes(b)}]),c()}catch(a){c(a)}},!1),735502,a=>a.a(async(b,c)=>{try{var d=a.i(12208),e=a.i(569572),f=a.i(884780),g=a.i(762008),h=a.i(641301),i=a.i(221214),j=a.i(446957),k=a.i(344853),l=a.i(947950),m=a.i(986743),n=a.i(138100),o=a.i(684321),p=a.i(821415),q=a.i(706210),r=a.i(182248),s=a.i(644468),t=a.i(938934),u=b([i,k,l,m,n,s]);async function v(a,b,c,f){var u,v,y,z,A,B,C,D,E,F;let G,H,I,J,K,L,M,N=await (0,p.openWorkspace)(),O=a.trim(),[P,Q,R,S,T,U,V,W,X]=await Promise.all([(0,n.loadSkills)(N,O),(0,m.listNoteIndex)(),(0,s.listConnectedToolNames)(),(0,l.findPinnedTools)(O),(0,i.listJobBots)(),(0,h.listBotMemory)(O),(0,i.readBotMemoryOn)(),(0,p.readMachineTools)(N),(0,k.listBotWork)(O,c?.thread??null)]),Y=T.filter(a=>a.name!==O),Z=T.find(a=>a.name===O)??await (0,i.findJobBot)(O),$=[(u=O,v=Z,y=c,H=(G=y?.owner??u)===u?"**You** coordinate this thread: its result goes from you to Thursday.":`**${G}** coordinates this thread and brings its result to Thursday.`,I=y?`
|
|
1
|
+
module.exports=[652619,a=>a.a(async(b,c)=>{try{var d=a.i(666680),e=a.i(347299),f=a.i(345364),g=a.i(47919),h=a.i(868468),i=a.i(53112),j=a.i(569572),k=a.i(725466),l=a.i(176668),m=a.i(523095),n=a.i(293480),o=a.i(8412),p=a.i(182248),q=a.i(689656),r=b([k]);[k]=r.then?(await r)():r;let C="app_EMoamEEZ73f0CkXaXp7hrann",D="http://localhost:1455/auth/callback",E=["127.0.0.1","::1"],F="thursday",{apiKeyName:G,label:H}=q.TEXT_MODEL_PROVIDERS.chatgpt,I=`${H} is not signed in — sign in from Settings › API keys.`,J=i.z.object({access:i.z.string().min(1),refresh:i.z.string().min(1),expires:i.z.number(),accountId:i.z.string().min(1),plan:i.z.string().nullable()}),K=globalThis,L=K.__chatgptRenewal??=(0,o.createKeyedLock)();async function s(){t();let a=(0,d.randomBytes)(32).toString("base64url"),b=(0,d.randomBytes)(16).toString("hex"),c=[],f=(d,e)=>{u(d.url??"/",{state:b,verifier:a}).then(a=>{e.writeHead(a.status,{"content-type":"text/html; charset=utf-8"}),e.end((0,m.oauthPage)(a.title,a.detail,{autoClose:200===a.status}),()=>{a.last&&K.__chatgptListeners===c&&t()})})};for(let a of E){let b=(0,e.createServer)(f),d=await new Promise(c=>{b.once("error",c),b.listen(1455,a,()=>c(null))});if(!d){c.push(b);continue}if("EADDRNOTAVAIL"!==d.code&&"EAFNOSUPPORT"!==d.code){for(let a of c)a.close();(0,n.publicError)("EADDRINUSE"===d.code?"Port 1455 is in use by another app — often a ChatGPT or Codex sign-in still waiting. Finish or close it, then try again.":`Could not wait for the sign-in: ${(0,p.errorToString)(d)}`)}}K.__chatgptListeners=c,setTimeout(()=>{K.__chatgptListeners===c&&t()},j.CHATGPT_SIGN_IN.waitMs).unref();let g=new URL("https://auth.openai.com/oauth/authorize");return g.search=new URLSearchParams({response_type:"code",client_id:C,redirect_uri:D,scope:"openid profile email offline_access",code_challenge:(0,d.createHash)("sha256").update(a).digest("base64url"),code_challenge_method:"S256",state:b,id_token_add_organizations:"true",codex_cli_simplified_flow:"true",originator:F}).toString(),g.toString()}function t(){let a=K.__chatgptListeners;for(let b of(K.__chatgptListeners=null,a??[]))b.close(),b.closeIdleConnections()}async function u(a,b){let c=new URL(a,D);if("/auth/callback"!==c.pathname)return{status:404,title:"Not found",detail:"",last:!1};let d=c.searchParams.get("error");if(d){let a=c.searchParams.get("error_description");return{status:400,title:"Sign-in failed",detail:a?`${d}: ${a}`:d,last:!0}}let e=c.searchParams.get("code");if(!e||c.searchParams.get("state")!==b.state)return{status:400,title:"Sign-in failed",detail:"This is not the sign-in that was started. Start again from Settings › API keys.",last:!1};try{let a=await v({grant_type:"authorization_code",code:e,code_verifier:b.verifier,redirect_uri:D});return await (0,k.writeConfig)(G,JSON.stringify(a)),{status:200,title:"Signed in to ChatGPT",detail:"Bots can run on your plan now. This window closes itself.",last:!0}}catch(a){return l.logger.warn({cause:a},"chatgpt sign-in failed"),{status:502,title:"Sign-in failed",detail:(0,p.errorToString)(a),last:!0}}}async function v(a){let b=await fetch("https://auth.openai.com/oauth/token",{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:C,...a})}).catch(a=>{l.logger.warn({cause:a},"chatgpt token endpoint unreachable"),(0,n.publicError)("Could not reach ChatGPT's sign-in")}),c=await b.json().catch(()=>null),d=c?.access_token;if(!b.ok||!d){let a=c?.error,d="string"==typeof a?[a,c?.error_description].filter(Boolean).join(": "):a?.message??a?.code??"";(0,n.publicError)(`ChatGPT's sign-in answered ${b.status}${d?`: ${d}`:""}`)}let e=function(a){try{let b=JSON.parse(Buffer.from(a.split(".")[1]??"","base64url").toString("utf8")),c=b["https://api.openai.com/auth"]??{};return{accountId:"string"==typeof c.chatgpt_account_id?c.chatgpt_account_id:null,plan:"string"==typeof c.chatgpt_plan_type?c.chatgpt_plan_type:null,expires:"number"==typeof b.exp?1e3*b.exp:null}}catch{return{accountId:null,plan:null,expires:null}}}(d),f=c?.refresh_token??a.refresh_token;e.accountId&&f||(0,n.publicError)("ChatGPT's sign-in came back without an account");let g=c?.expires_in;return{access:d,refresh:f,expires:"number"==typeof g?Date.now()+1e3*g:e.expires??Date.now(),accountId:e.accountId,plan:e.plan}}async function w(){let a=await (0,k.readConfig)(G);if(!a)return null;try{return J.parse(JSON.parse(a))}catch{return null}}let M=a=>a.expires-j.CHATGPT_SIGN_IN.renewBeforeMs<=Date.now();async function x(){let a=await w();return(a||(0,n.publicError)(I),M(a))?L(G,async()=>{let a=await w();if(a||(0,n.publicError)(I),!M(a))return a;try{let b=await v({grant_type:"refresh_token",refresh_token:a.refresh});return await (0,k.writeConfig)(G,JSON.stringify(b)),b}catch(a){(0,n.publicError)(`Could not renew the ${H} sign-in (${(0,p.errorToString)(a)}). If it keeps failing, sign in again from Settings › API keys.`)}}):a}async function y(){return(await w())?.plan??null}async function z(a,b){let c=await x(),d=new Headers(b?.headers);if(d.set("authorization",`Bearer ${c.access}`),d.set("chatgpt-account-id",c.accountId),d.set("originator",F),b?.method!=="POST"||"string"!=typeof b.body||!String(a).endsWith("/responses"))return fetch(a,{...b,headers:d});let e=JSON.parse(b.body),f=!0===e.stream,g=[];e.input=(e.input??[]).filter(a=>"system"!==a.role&&"developer"!==a.role||(g.push("string"==typeof a.content?a.content:(a.content??[]).map(a=>a.text??"").join("\n")),!1)),e.instructions=[e.instructions,...g].filter(Boolean).join("\n\n")||"You are a helpful assistant.",e.store=!1,e.stream=!0,e.max_output_tokens=void 0,d.set("accept","text/event-stream");let h=await fetch(a,{...b,headers:d,body:JSON.stringify(e)});return 429===h.status?A(h):f||!h.ok?h:B(h)}async function A(a){let b=await a.text(),c={};try{c=JSON.parse(b).error??{}}catch{}if(!/usage_limit_reached|usage_not_included/.test(`${c.code} ${c.type}`)){let c=a.headers.get("retry-after");return new Response(b,{status:429,headers:{"content-type":"application/json",...c?{"retry-after":c}:{}}})}let d=c.resets_at?1e3*c.resets_at:c.resets_in_seconds?Date.now()+1e3*c.resets_in_seconds:null,e=c.plan_type?` on the ${c.plan_type} plan`:"",f=d?` It resets in ${(0,h.formatDistanceToNowStrict)(d)}.`:"";return Response.json({error:{message:`${H} usage limit reached${e}.${f}`,code:c.code??c.type}},{status:402})}async function B(a){let b=[],c=null,d=null;for(let e of(await a.text()).replaceAll("\r\n","\n").split("\n\n")){let a,f=e.split("\n").filter(a=>a.startsWith("data:")).map(a=>a.slice(5).trimStart()).join("\n");if(f&&"[DONE]"!==f){try{a=JSON.parse(f)}catch{continue}"response.output_item.done"===a.type?b.push(a.item):"response.completed"===a.type||"response.incomplete"===a.type?c=a.response??{}:"response.failed"===a.type?d=a.response?.error??{message:"The response failed"}:"error"===a.type&&(d={code:a.code,message:a.message})}}return d||!c?Response.json({error:{message:d?.message??"The stream ended before the response finished",code:d?.code}},{status:d?.code==="context_length_exceeded"?400:500}):Response.json({...c,output:c.output?.length?c.output:b})}a.s(["chatGptModel",0,function(a){let b=(0,f.createOpenAI)({baseURL:"https://chatgpt.com/backend-api/codex",apiKey:"signed-in",headers:{"OpenAI-Beta":"responses=experimental"},fetch:z}),c=(0,d.randomUUID)();return(0,g.wrapLanguageModel)({model:b.responses(a),middleware:{transformParams:async({params:a})=>({...a,providerOptions:{...a.providerOptions,openai:{promptCacheKey:c,...a.providerOptions?.openai,store:!1,includeWebSearchSources:!1}}})}})},"chatGptSearch",0,()=>(0,f.createOpenAI)({apiKey:"signed-in"}).tools.webSearch(),"readChatGptPlan",0,y,"startChatGptSignIn",0,s]),c()}catch(a){c(a)}},!1),884780,a=>{"use strict";a.i(902157),a.i(912714);var b=a.i(750227),c=a.i(569572);(0,b.join)(c.APP_DIR,"guide");let d=".guide";a.s(["botGuideLine",0,()=>`How ${c.APP_NAME} itself works for the user — its screens and settings — is written under \`${d}/\` here, \`index.md\` first; read it only when the job is about the app.`,"guideLine",0,()=>`How ${c.APP_NAME} works for the person using it — its screens, its settings, what it connects to, what to do when something stops — is written under \`${d}/\` here, \`index.md\` first. Read it whenever an answer depends on how the app works: what can be asked for, where something is changed, a wish that needs a setting switched on, something that stopped or was refused. Answer from it rather than from what you assume.`])},738131,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(868468),f=a.i(569572),g=a.i(875931),h=a.i(938934),i=a.i(978876),j=a.i(375827),k=a.i(127507),l=a.i(467650),m=a.i(138902),n=a.i(345846),o=a.i(617594),p=a.i(622547),q=a.i(128232),r=a.i(382442),s=a.i(451017),t=a.i(762008),u=a.i(547613),v=a.i(446957),w=a.i(138100),x=a.i(821415),y=a.i(706210),z=a.i(176668),A=a.i(293480),B=a.i(987674),C=a.i(182248),D=b([g,i,m,n,o,p,q,s,w]);async function E(b){let{listThreadOverview:c}=await a.A(343064),d=await c();if(!d.length)return"No thread has been started yet.";let e=d.map(a=>`"${a.label}" (${a.bot}, ${a.status})`).join(", ");return`There is no thread called "${b}". The latest are: ${e}. Call again with one of those labels.`}async function F(a,b){let c=[];for(let[a,e]of Object.entries(b)){let b=await (0,d.asSchema)(e.inputSchema).jsonSchema,f="string"==typeof e.description?e.description:"";c.push({name:a,tokens:(0,B.estimateTokens)(f)+(0,B.estimateTokens)(JSON.stringify(b))})}c.sort((a,b)=>b.tokens-a.tokens);let e=c.reduce((a,b)=>a+b.tokens,0);z.logger.debug(`${a} tools ${e} tokens over ${c.length} — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`)}async function G(a){let b=await H(a);return f.IS_DEV&&await F(a.target,b),b}async function H(b){if("memory-edit"===b.target)return(0,n.createMemoryTools)("user",null,{countReads:!1});let c=(0,n.createMemoryTools)("call","thursday"===b.target?b.callId??null:null),z=await (0,x.openWorkspace)();if("thursday"===b.target){var B;let k,m,n=b.readSkills?(0,s.createSkillTools)({sandbox:z,skills:await (0,w.loadSkills)(z)}):{},q=!!(b.written&&b.model&&(0,g.seesToolImages)(b.model));return{...c,...n,...(0,u.createWorkspaceTools)(z,{write:!1,timeoutMs:f.CALL_EXEC_TIMEOUT_MS}),...!1===b.webSearch?{}:await (0,p.createCallSearchTool)(z),...Object.fromEntries(Object.entries((B=b.callId,k=async b=>{let{resolveThread:c}=await a.A(343064);return(b.trim()?await c(b.trim()):null)??await E(b)},m=async(b,c,d)=>{let e=await a.A(763543);try{return await e.answerThread(b,c,"thursday",d)}catch(a){if((0,A.isPublicError)(a))return a.message;throw a}},{[t.TOOL_NAMES.thread_start]:(0,d.tool)({description:i.threadStartSpec.description,inputSchema:i.threadStartSpec.parameters,execute:async({bot:b,request:c,label:d})=>{let{findJobBot:e,listJobBots:f}=await a.A(276307),g=await e(b);if(!g||g.disabled){let a=(await f()).map(a=>a.name);return`There is no bot called "${b}". The bots are: ${a.join(", ")}. Nothing was started — call again with one of those.`}let{startThread:h}=await a.A(763543);return{threadId:await h({bot:g.name,request:c,label:d,callId:B,from:"thursday"}),bot:g.name,label:d,note:`${g.name} has "${d}". Its updates reach the conversation on their own. Anything further about this work — a correction, the next step once it finishes — is \`${t.TOOL_NAMES.thread_tell}\` with "${d}"; a question it asks is answered with \`${t.TOOL_NAMES.thread_answer}\`.`}}}),[t.TOOL_NAMES.thread_tell]:(0,d.tool)({description:i.threadTellSpec.description,inputSchema:i.threadTellSpec.parameters,execute:async({thread:a,words:b})=>{let c=await k(a);if("string"==typeof c)return c;if(!b.trim())return"Say what to pass on.";let d=await m(c.id,b.trim());return"string"==typeof d?d:d?.answered?{label:c.label,answered:d.answered,note:`${d.answered.bot} was waiting on a question, and took this as its answer.`}:{label:c.label,bot:d?.to??c.bot,status:"running",note:"running"===c.status?"The bot reads it before its next step.":"The bot picks the thread back up from there."}}}),[t.TOOL_NAMES.thread_answer]:(0,d.tool)({description:i.threadAnswerSpec.description,inputSchema:i.threadAnswerSpec.parameters,execute:async({thread:b,bot:c,answer:d})=>{let e=await k(b);if("string"==typeof e)return e;if(!d.trim())return"Say what the answer is.";let{findThreadView:f}=await a.A(343064),g=(await f(e.id))?.room.questions??[],h=g.find(a=>a.bot.toLowerCase()===c.trim().toLowerCase());if(!h)return g.length?`${c} is not asking anything in "${e.label}". Waiting there: ${g.map(a=>a.bot).join(", ")}. Call again with that bot.`:`No question is waiting in "${e.label}". To say something else to it, use \`${t.TOOL_NAMES.thread_tell}\`.`;let i=await m(e.id,d.trim(),h.bot);return"string"==typeof i?i:{label:e.label,answered:i?.answered??{bot:h.bot,question:h.text},note:`${h.bot} has the answer to its question and goes on from it.`}}}),[t.TOOL_NAMES.thread_status]:(0,d.tool)({description:i.threadStatusSpec.description,inputSchema:i.threadStatusSpec.parameters,execute:async({thread:b})=>{let{listThreadOverview:c,findThreadView:d}=await a.A(343064),g={now:(0,h.clockNow)()},i=a=>(0,e.formatDistanceToNowStrict)((0,y.toDate)(a),{addSuffix:!0});if(!(!b.trim()||"all"===b.trim().toLowerCase())){let a=await k(b);if("string"==typeof a)return a;let c=(await d(a.id))?.room;return{...g,label:a.label,id:a.id,bot:a.bot,participants:c?.participants??[],questions:c?.questions??[],status:a.status,since:i(a.updatedAt),outcome:a.outcome,..."waiting"===a.status&&a.pending?.options.length?{options:a.pending.options}:{}}}let j=await c();return j.length?{...g,threads:j.map(a=>({id:a.id,label:a.label,bot:a.bot,status:a.status,participants:a.room.participants,questions:a.room.questions.map(a=>({...a,text:(0,C.clip)(a.text,f.PROMPT_LINE.threadStatus)})),since:i(a.updatedAt),...a.ask?{asking:a.ask.question,options:a.ask.options}:{},..."running"===a.status?{now:(0,v.threadActivity)(a.lines)}:{},...a.outcome&&"waiting"!==a.status?{outcome:(0,C.clip)(a.outcome,f.PROMPT_LINE.threadStatus)}:{}}))}:"No thread has been started yet."}}),[t.TOOL_NAMES.thread_cancel]:(0,d.tool)({description:i.threadCancelSpec.description,inputSchema:i.threadCancelSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{cancelThread:d}=await a.A(763543);return await d(c.id),{label:c.label,status:"cancelled"}}}),[t.TOOL_NAMES.thread_show]:(0,d.tool)({description:i.threadShowSpec.description,inputSchema:i.threadShowSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{appEvents:d}=await a.A(133300),{filesOnDisk:e}=await a.A(122690),{leadFirst:f,pathsIn:g,viewKindOf:h}=await a.A(394298),i=(await e(g(c.outcome??""),null)).filter(a=>"none"!==h(a));if(!i.length)return d.emit({type:"showThread",threadId:c.id}),{label:c.label,showing:"the thread"};let j=f(i);d.emit({type:"showFile",paths:j});let{markSeen:l}=await a.A(343064);return await l([c.id]),{label:c.label,showing:j[0]}}}),[t.TOOL_NAMES.thread_seen]:(0,d.tool)({description:i.threadSeenSpec.description,inputSchema:i.threadSeenSpec.parameters,execute:async({thread:b})=>{let c=await k(b);if("string"==typeof c)return c;let{markSeen:d}=await a.A(343064);return await d([c.id]),{label:c.label,seen:!0}}})})).filter(([a])=>!(b.phone&&a===t.TOOL_NAMES.thread_show))),...(0,o.createRoutineTools)(),...q?(0,l.createLookTool)():{},...b.written?{}:(0,j.callTools)()}}let D=await (0,w.loadSkills)(z,b.bot),F={...(0,x.jobShellEnv)(b.session),...(0,x.botShellEnv)(b.bot,(await (await a.A(276307)).findJobBot(b.bot))?.icon)},G=!!(b.model&&(0,g.seesToolImages)(b.model.ref));return{[t.TOOL_NAMES.memory_recall]:(0,n.createMemoryTools)("call",null,{tidies:!1})[t.TOOL_NAMES.memory_recall],...await (0,p.createSearchTool)(b.model,z),...(0,u.createWorkspaceTools)(z,{write:!0,env:F,guide:!0,bot:b.bot}),...await (0,m.createMcpTools)(b.bot,z),...(0,s.createSkillTools)({sandbox:z,skills:D,bot:b.bot}),...await (0,q.createSelfTools)(b.bot),...(0,k.createDeckTools)(z,b.bot,F,G),...G?(0,l.createLookTool)():{},...(0,r.createSignInTools)(z,b.bot,(0,x.jobShellEnv)(b.session)),...await (0,i.createThreadRecallTool)(b.bot,b.thread??null)}}[g,i,m,n,o,p,q,s,w]=D.then?(await D)():D,a.s(["loadTools",0,G]),c()}catch(a){c(a)}},!1),875931,a=>a.a(async(b,c)=>{try{var d=a.i(938537),e=a.i(674861),f=a.i(606016),g=a.i(388319),h=a.i(538177),i=a.i(767071),j=a.i(140358),k=a.i(873739),l=a.i(899042),m=a.i(345364),n=a.i(434451),o=a.i(655819),p=a.i(652685),q=a.i(156956),r=a.i(47919),s=a.i(569572),t=a.i(688034),u=a.i(725466),v=a.i(176668),w=a.i(293480),x=a.i(182248),y=a.i(652619),z=a.i(689656),A=b([u,y]);[u,y]=A.then?(await A)():A;let N=/context[ _-]?(length|window)|maximum context|prompt is too long|too many (input )?tokens|input token count|exceeds? the (maximum|model'?s?) (context|input|prompt|number of tokens)|maximum prompt length|request (entity )?too large/i;function B(a){return C(a).some(a=>{let{statusCode:b,message:c,error:d}=a;if(void 0!==b&&400!==b&&413!==b)return!1;let e=p.APICallError.isInstance(a)?a.responseBody:null;return[c,d,e].some(a=>"string"==typeof a&&N.test(a))})}let O=new Set([408,409,429]);function C(a){let b=[],c=[a];for(;c.length&&b.length<12;){let a=c.shift();!("object"!=typeof a||null===a||b.includes(a))&&(b.push(a),r.RetryError.isInstance(a)&&c.push(...a.errors),"cause"in a&&c.push(a.cause))}return b}let P=(a,b)=>({ref:a,model:b,searchTools:null}),Q=null;function D(a){if(null==a||""===a)return null;let b=Number(a);return Number.isFinite(b)?Math.round(1e6*b*1e4)/1e4:null}async function E(){if(Q&&Date.now()-Q.at<s.GATEWAY_CATALOG_MS)return Q.models;let a=await fetch("https://ai-gateway.vercel.sh/v1/models",{headers:{accept:"application/json"}}).catch(a=>{v.logger.warn({cause:a},"gateway catalog unreachable"),(0,w.publicError)("Could not reach the gateway")});a.ok||(0,w.publicError)(`The gateway answered ${a.status}`);let b=((await a.json()).data??[]).filter(a=>!!a.id).map(a=>{let b,c;return{id:a.id,label:a.name||a.id,owner:a.owned_by||a.id.slice(0,a.id.indexOf("/")),type:a.type??null,tags:a.tags??[],price:function(a){let b=a.pricing??{},c=D(b.input),d=D(b.output);if((a.tags??[]).includes("free")||0===c)return{in:0,out:0,note:null,free:!0};let e=b.transcription_duration_cost_per_second??b.realtime_session_duration_cost_per_second;if(e)return{in:null,out:null,note:`$${e}/s`,free:!1};if(b.speech_input_character_cost)return{in:null,out:null,note:"per character",free:!1};let f=Array.isArray(b.video_duration_pricing)?b.video_duration_pricing[0]:null;if(f?.cost_per_second)return{in:null,out:null,note:`$${f.cost_per_second}/s ${f.resolution??""}`.trimEnd(),free:!1};let g=b.image?`$${b.image}/image`:b.image_dimension_quality_pricing?"per image, by size":null;return null===c&&null===d?{in:null,out:null,note:g,free:!1}:{in:c,out:d,note:b.input_tiers?"tiered":b.varies_by_provider?"varies":g&&"+ per image",free:!1}}(a),retiring:!!a.deprecated_at,contextWindow:"number"==typeof a.context_window&&a.context_window>0?a.context_window:null,efforts:(b=(a.reasoning_options??[]).find(a=>a?.type==="effort"),(c=z.EFFORTS.filter(a=>b?.values?.includes(a))).length?c:null)}}).sort((a,b)=>a.id.localeCompare(b.id));return Q={at:Date.now(),models:b},b}async function F(a,b){if(b&&b>0)return b;let c=await G(a);return(0,z.compactAtFor)((0,z.contextWindowOf)(a.provider,a.model,c))}async function G(a){return"vercel-ai-gateway"!==a.provider?[]:await E().catch(()=>[])}async function H(a,b){let c=b??z.effortSchema.safeParse(await (0,u.readConfig)(t.DEFAULT_EFFORT_KEY)).data;if(!c)return;let d=await G(a);return(0,z.effortsOf)(a.provider,a.model,d)?.includes(c)?c:void 0}async function I(){return await E().then(a=>new Set(a.map(a=>a.id))).catch(()=>null)}async function J(a,b){if("vercel-ai-gateway"!==a)return b;let c=await I();if(!c)return b;let d=b.filter(a=>c.has(a.id));return d.length>0?d:b}async function K(a){let{label:b,apiKeyName:c,signIn:p}=z.TEXT_MODEL_PROVIDERS[a.provider],r=await (0,u.readConfig)(c);return r||(0,w.publicError)(p?`${b} is not signed in — sign in from Settings › API keys.`:`No ${b} key — add one in Settings › API keys.`),function(a,b){switch(a.provider){case"openai":{let c=(0,m.createOpenAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"chatgpt":return{ref:a,model:(0,y.chatGptModel)(a.model),searchTools:{search:(0,y.chatGptSearch)()}};case"anthropic":{let c=(0,d.createAnthropic)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch_20260209()}}}case"google":{let c=(0,j.createGoogleGenerativeAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.googleSearch({})}}}case"xai":{let c=(0,o.createXai)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"mistral":return P(a,(0,l.createMistral)({apiKey:b})(a.model));case"deepseek":return P(a,(0,h.createDeepSeek)({apiKey:b})(a.model));case"groq":return P(a,(0,k.createGroq)({apiKey:b})(a.model));case"cerebras":return P(a,(0,e.createCerebras)({apiKey:b})(a.model));case"togetherai":return P(a,(0,n.createTogetherAI)({apiKey:b})(a.model));case"fireworks":return P(a,(0,i.createFireworks)({apiKey:b})(a.model));case"deepinfra":return P(a,(0,g.createDeepInfra)({apiKey:b})(a.model));case"cohere":return P(a,(0,f.createCohere)({apiKey:b})(a.model));case"vercel-ai-gateway":{let c=(0,q.createGateway)({apiKey:b});return{ref:a,model:c(a.model),searchTools:null}}default:(0,w.publicError)(`Not supported provider: ${String(a.provider)}`)}}(a,r)}async function L(a,{quiet:b=!1}={}){let c=async a=>(0,z.defaultModelOf)({defaultTier:"chatgpt"===a.id&&await (0,y.readChatGptPlan)()==="free"?"small":a.defaultTier,suggestModels:await J(a.id,a.suggestModels)}),d=a?z.TEXT_MODEL_PROVIDER_LIST.find(b=>b.id===a):void 0,e=["chatgpt","openai","xai"].map(a=>({...z.TEXT_MODEL_PROVIDERS[a],id:a}));if(d){let a=await c(d);if(a)return{provider:d.id,model:a}}let f=(0,z.parseTextModel)(await (0,u.readConfig)(t.DEFAULT_MODEL_KEY)??void 0);if(f){let{label:a,apiKeyName:b,signIn:c}=z.TEXT_MODEL_PROVIDERS[f.provider];if(await (0,u.readConfig)(b))return f;(0,w.publicError)(c?`The default model is ${f.model} on ${a}, which is signed out — sign in again, or pick another in Settings › Models.`:`The default model is ${f.model}, and there is no ${a} key any more — add it in Settings › API keys, or pick another in Settings › Models.`)}for(let a of[...e,...z.TEXT_MODEL_PROVIDER_LIST]){if(!await (0,u.readConfig)(a.apiKeyName))continue;let d=await c(a);if(d)return b||v.logger.info(`no model set, falling back to ${a.id}/${d}`),{provider:a.id,model:d}}(0,w.publicError)("No model key is set — add one in Settings › API keys.")}async function M(a){let b=(0,z.parseMediaModel)(await (0,u.readConfig)(t.MEDIA_MODEL_KEYS[a]));if(!b||!(0,z.canMakeKind)(b.provider,a))return null;let c=await (0,u.readConfig)(z.MEDIA_MODEL_PROVIDERS[b.provider].apiKeyName);return c?{ref:b,apiKey:c}:null}a.s(["buildImageModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).image(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).image(a.model);case"xai":return(0,o.createXai)({apiKey:b}).image(a.model);case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).image(a.model);default:(0,w.publicError)(`Not supported image provider: ${String(a.provider)}`)}},"buildSpeechModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).speech(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).speech(a.model);case"xai":return(0,o.createXai)({apiKey:b}).speech();case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).speech(a.model);default:(0,w.publicError)(`Not supported speech provider: ${String(a.provider)}`)}},"buildTranscriptionModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).transcription(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).transcription(a.model);case"xai":return(0,o.createXai)({apiKey:b}).transcription();case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).transcription(a.model);default:(0,w.publicError)(`Not supported transcription provider: ${String(a.provider)}`)}},"buildVideoModel",0,function(a,b){switch(a.provider){case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).video(a.model);case"xai":return(0,o.createXai)({apiKey:b}).video(a.model);case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).video(a.model);default:(0,w.publicError)(`${a.provider} has no video model`)}},"compactBudget",0,F,"getTextModel",0,K,"isContextOverflow",0,B,"isProviderRefusal",0,function(a){return!B(a)&&C(a).some(a=>{let{statusCode:b}=a;return"number"==typeof b&&b>=400&&b<500&&!O.has(b)})},"modelErrorToString",0,function(a){if(!p.APICallError.isInstance(a))return(0,x.errorToString)(a);let b=a.statusCode?` (${a.statusCode})`:"",c=a.responseBody?.trim(),d=c&&!c.includes(a.message)?` ${(0,x.clip)(c,300)}`:"";return`${a.message}${b}${d}`},"resolveDefaultModel",0,L,"resolveMediaRef",0,M,"runEffort",0,H,"seesToolImages",0,function(a){let b="vercel-ai-gateway"===a.provider?z.GATEWAY_OWNERS[a.model.split("/")[0]]:a.provider;return void 0!==b&&["openai","chatgpt","anthropic","google","xai"].includes(b)}]),c()}catch(a){c(a)}},!1),735502,a=>a.a(async(b,c)=>{try{var d=a.i(12208),e=a.i(569572),f=a.i(884780),g=a.i(762008),h=a.i(641301),i=a.i(221214),j=a.i(446957),k=a.i(636616),l=a.i(344853),m=a.i(947950),n=a.i(986743),o=a.i(138100),p=a.i(684321),q=a.i(821415),r=a.i(706210),s=a.i(182248),t=a.i(644468),u=a.i(938934),v=b([i,l,m,n,o,t]);async function w(a,b,c,f){var k,v,w,z,A,B,C,D,E,F;let G,H,I,J,K,L,M,N=await (0,q.openWorkspace)(),O=a.trim(),[P,Q,R,S,T,U,V,W,X]=await Promise.all([(0,o.loadSkills)(N,O),(0,n.listNoteIndex)(),(0,t.listConnectedToolNames)(),(0,m.findPinnedTools)(O),(0,i.listJobBots)(),(0,h.listBotMemory)(O),(0,i.readBotMemoryOn)(),(0,q.readMachineTools)(N),(0,l.listBotWork)(O,c?.thread??null)]),Y=T.filter(a=>a.name!==O),Z=T.find(a=>a.name===O)??await (0,i.findJobBot)(O),$=[(k=O,v=Z,w=c,H=(G=w?.owner??k)===k?"**You** coordinate this thread: its result goes from you to Thursday.":`**${G}** coordinates this thread and brings its result to Thursday.`,I=w?`
|
|
2
2
|
|
|
3
|
-
Current conversation: ${
|
|
4
|
-
Others know you as: ${(0,j.rosterLine)(v)}`:"",`You are ${
|
|
3
|
+
Current conversation: ${w.caller} → ${k}. Your final text goes back to ${w.caller}.`:"",J=v?`
|
|
4
|
+
Others know you as: ${(0,j.rosterLine)(v)}`:"",`You are ${k}, one of the bots in this thread. ${(0,u.nowLine)()}${J}
|
|
5
5
|
|
|
6
6
|
- **The user** — the one person all of this is for. They talk with Thursday by voice and follow this thread on their screen.
|
|
7
7
|
- **Thursday** — their personal assistant. She talks with them, hands bots the work that takes time, and tells them what comes back.
|
|
@@ -16,21 +16,21 @@ What Thursday keeps from talking with them. When the job needs something about t
|
|
|
16
16
|
|
|
17
17
|
path — what it is about (facts)
|
|
18
18
|
|
|
19
|
-
${(0,
|
|
19
|
+
${(0,u.noteLines)(z)}`),function(a,b){let c=new Set(b.map(a=>`${a.server}/${a.name}`)),d=a.filter(a=>!c.has(`${a.server}/${a.name}`));if(0===d.length)return"";let e=c.size?" The ones you already hold are in your tools instead.":"";return`## Connected tools
|
|
20
20
|
|
|
21
|
-
${(0,
|
|
21
|
+
${(0,u.mcpToolLines)(d)}
|
|
22
22
|
|
|
23
23
|
Names only: \`${g.TOOL_NAMES.tool_search}\` returns what each one takes, \`${g.TOOL_NAMES.tool_call}\` runs one.${e}`}(R,S),(A=P,0===A.length?"":`## Skills
|
|
24
24
|
|
|
25
25
|
Written-down ways of doing things. Open one with \`${g.TOOL_NAMES.load_skill}\` before a job it covers, unless its instructions are already in your conversation.
|
|
26
26
|
|
|
27
|
-
${(0,
|
|
27
|
+
${(0,u.skillLines)(A)}`),y(N.cwd,W,f),V?(B=(0,h.botMemoryFolder)(O),K=(C=U).entries.length?C.entries.map(({file:a,line:b,at:c})=>{let f=b?` — ${(0,s.clip)(b,e.PROMPT_LINE.botMemory)}`:"";return`- ${a}${f} \xb7 ${(0,d.format)((0,r.toDate)(c),"yyyy-MM-dd")}`}).join("\n"):"Empty.",L=C.total>C.entries.length?`
|
|
28
28
|
|
|
29
29
|
The newest ${C.entries.length} of ${C.total}; \`ls ${B}\` for the rest.`:"",`## Your memory
|
|
30
30
|
|
|
31
31
|
What you learned on your own earlier jobs, in \`${B}/\`: one topic per file, its first line saying what it holds, read by no other bot, up to ${e.BOT_MEMORY_LIMITS.files} files of ${e.BOT_MEMORY_LIMITS.chars.toLocaleString("en-US")} characters each. It is how you get better at this work. When a job teaches you something a later one would otherwise find out again — how a site signs in, the way through its screens, a command that turned out right — or the user asks you to remember how to work, keep it with the date it was true, and fix or delete what proved wrong. No passwords, keys or codes.
|
|
32
32
|
|
|
33
|
-
${K}${L}`):"",function(a,b){if(!b.open.length&&!b.recent.length)return"";let c=b=>{let c=b.said?` — ${(0,
|
|
33
|
+
${K}${L}`):"",function(a,b){if(!b.open.length&&!b.recent.length)return"";let c=b=>{let c=b.said?` — ${(0,s.clip)(b.said,e.BOT_WORK.said)}`:"",d=b.said?(0,p.pathsIn)(b.said).slice(0,e.BOT_WORK.files):[],f=d.length?` \xb7 ${d.map(a=>`\`${a}\``).join(", ")}`:"";return`- ${b.cut?`[${(0,j.workHandle)(b.id)}] `:""}${(0,u.botWorkHead)(b,a)}${c}${f}`},d=(a,b)=>b.length?`${a}
|
|
34
34
|
${b.map(c).join("\n")}`:"",f=[...b.open,...b.recent].some(a=>a.cut)?` A line with an id in brackets was cut short: \`${g.TOOL_NAMES.thread_recall}\` opens that one whole, for when this job builds on it.`:"";return`## Your other threads
|
|
35
35
|
|
|
36
36
|
Your threads besides this one. You remember none of them here: each line is where it stands, your own last words there, and the files those words name.${f}
|
|
@@ -39,19 +39,23 @@ ${[d("Open",b.open),d("Ended",b.recent)].filter(Boolean).join("\n")}`}(O,X),(D=Y
|
|
|
39
39
|
|
|
40
40
|
${D.map(a=>`- **${a.name}** — ${(0,j.rosterLine)(a)}`).join("\n")}
|
|
41
41
|
|
|
42
|
-
These lines were written for the user: where one says "you", it means them. When part of the job is another bot's strength, bring it in with \`${g.TOOL_NAMES.send_message}\` rather than rebuilding it yourself.`),(E=O,F=c,M=(F?.owner??E)===E?"Bring what you received together into one result for Thursday: what was done, where it is, what you decided that the request did not say, and what is still open, at the detail the user asked for. Every file you name in it is drawn under your words in the thread and waits in the screen's corner for the user to open, so name each one you want them to see — the page to read first, then the rest.":`Your final text is your answer to ${F?.caller??"whoever asked"}, and all they see of your work: give them everything they need to carry on. When you cannot go on without something from them, end with that question instead; their reply brings you back with all you have done still in front of you.`,`## Working together
|
|
42
|
+
These lines were written for the user: where one says "you", it means them. When part of the job is another bot's strength, bring it in with \`${g.TOOL_NAMES.send_message}\` rather than rebuilding it yourself.`),(E=O,F=c,M=(F?.owner??E)===E?"While work you handed out is still out, your result waits for it: end your turn and its answer wakes you; write the result once everything you asked for is in. Bring what you received together into one result for Thursday: what was done, where it is, what you decided that the request did not say, and what is still open, at the detail the user asked for. Every file you name in it is drawn under your words in the thread and waits in the screen's corner for the user to open, so name each one you want them to see — the page to read first, then the rest.":`Your final text is your answer to ${F?.caller??"whoever asked"}, and all they see of your work: give them everything they need to carry on. When you cannot go on without something from them, end with that question instead; their reply brings you back with all you have done still in front of you.`,`## Working together
|
|
43
43
|
|
|
44
44
|
Nobody sees your work but you, and you see only what others send you, so whatever crosses between you has to stand on its own. A request says what is wanted, what is already known or done, and where the files are; an answer gives exact values, file paths and what is still unverified. Tell a bot you handed work to when what it depends on changes: it reads that before its next step. End your turn when you have nothing more to do now: replies arrive as new messages and wake you.
|
|
45
45
|
|
|
46
|
-
Ask Thursday with kind \`question\` only for a decision, permission or something only
|
|
46
|
+
Ask the user, through Thursday, with kind \`question\` only for a decision, permission or something only they know: clearly, with the context to answer, and short options when they help. Use kind \`message\` for news that needs no answer, and your final text for the result.
|
|
47
47
|
|
|
48
48
|
${M}
|
|
49
49
|
|
|
50
|
-
Write in the user's language, and name the paths of finished work. In Markdown, reference images by absolute route (\`/api/file/${e.PATHS.artifacts}/…\`).`),
|
|
50
|
+
Write in the user's language, and name the paths of finished work. In Markdown, reference images by absolute route (\`/api/file/${e.PATHS.artifacts}/…\`).`),x(O,b)].filter(Boolean).join("\n\n");return(0,u.logPromptSize)("bot",$),{text:$}}[i,l,m,n,o,t]=v.then?(await v)():v;let x=(a,b)=>{let c=b?.trim();return c?(0,k.findBotSeed)(a)?.systemPrompt.trim()===c?`## Your role
|
|
51
|
+
|
|
52
|
+
What this bot is for, as the app sets it up. Where it and anything above disagree, it wins.
|
|
53
|
+
|
|
54
|
+
${c}`:`## Owner's instructions
|
|
51
55
|
|
|
52
56
|
Written by the person this bot works for. Where these and anything above disagree, these win.
|
|
53
57
|
|
|
54
|
-
${
|
|
58
|
+
${c}`:""},y=(a,b,c)=>{var d;let h,i;return`## Environment
|
|
55
59
|
|
|
56
60
|
Current Cwd: ${a}
|
|
57
61
|
Platform: ${process.platform}
|
|
@@ -68,24 +72,24 @@ Your workspace, where \`${g.TOOL_NAMES.bash}\` runs. Everything you write goes i
|
|
|
68
72
|
|
|
69
73
|
Inside the workspace, set up whatever the job needs yourself; installing anything machine-wide waits for the user's yes. Never the directory above the workspace — it is the app's, not the user's; outside the workspace, only where the user pointed you.
|
|
70
74
|
|
|
71
|
-
${(0,f.botGuideLine)()}`};a.s(["buildThreadOpening",0,function(a){if(a.routine){let{when:b,last:c}=a.routine,f=c?` Its last run ended ${(0,d.format)(c.at,"yyyy-MM-dd HH:mm")}: ${(0,
|
|
75
|
+
${(0,f.botGuideLine)()}`};a.s(["buildThreadOpening",0,function(a){if(a.routine){let{when:b,last:c}=a.routine,f=c?` Its last run ended ${(0,d.format)(c.at,"yyyy-MM-dd HH:mm")}: ${(0,s.clip)(c.said,e.PROMPT_LINE.jobOutcome)}`:" This is its first run.";return[{type:"text",text:`You are ${a.bot}. A routine the user set up hands you this thread: it starts by itself, ${b}, and nobody is watching as it does.${f}`},{type:"text",text:`## The routine → ${a.bot}: the job
|
|
72
76
|
|
|
73
77
|
${a.request.trim()}`}]}let b="user"===a.from?"The user":"Thursday";return[{type:"text",text:`You are ${a.bot}. ${b} hands you this thread${"user"===a.from?" on screen":" during a call"}.`},{type:"text",text:`## ${b} → ${a.bot}: the job
|
|
74
78
|
|
|
75
|
-
${a.request.trim()}`}]},"loadBotPrompt",0,
|
|
79
|
+
${a.request.trim()}`}]},"loadBotPrompt",0,w]),c()}catch(a){c(a)}},!1),938934,a=>{"use strict";var b=a.i(12208),c=a.i(868468),d=a.i(569572),e=a.i(762008),f=a.i(951941),g=a.i(626550),h=a.i(706210),i=a.i(176668),j=a.i(987674),k=a.i(182248);let l=(a=new Date)=>`${(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm")} ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,m=(a=new Date)=>`**Now**: ${l(a)}`,n=a=>`${(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm")} (${(0,c.formatDistanceToNowStrict)(a,{addSuffix:!0})})`,o={[e.STUDIO_TOOLS.generate_image]:"images",[e.STUDIO_TOOLS.generate_speech]:"speech",[e.STUDIO_TOOLS.transcribe]:"transcription",[e.STUDIO_TOOLS.generate_video]:"video"};a.s(["botWorkHead",0,function(a,d){let e=(0,c.formatDistanceToNowStrict)(a.updatedAt,{addSuffix:!0}),f="running"===a.status?`running, last moved ${e}`:a.asking?`waiting on the user's answer since ${e}`:"waiting"===a.status?`stopped ${e}, not finished`:`${"done"===a.status?"ended":"stopped by the user"} ${(0,b.format)(a.updatedAt,"yyyy-MM-dd")}`;return`"${a.label}" — ${a.owner===d?"yours":`${a.owner}'s`} — ${f}`},"clockNow",0,l,"logPromptSize",0,function(a,b){let c=(0,j.sectionTokens)(b),e=c.reduce((a,b)=>a+b.tokens,0);i.logger.debug(`${a} prompt ${e} tokens — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`);let f=c[0];e>d.PROMPT_BUDGET&&f&&i.logger.warn(`${a} prompt is ${e} tokens, over ${d.PROMPT_BUDGET}: ${f.name} carries ${f.tokens} of it. Every call and every job pays this.`)},"mcpToolLines",0,function(a){let b=new Map;for(let c of a){let a=b.get(c.server);a?a.push(c.name):b.set(c.server,[c.name])}return[...b].map(([a,b])=>`- **${a}**: ${b.join(", ")}`).join("\n")},"noteLines",0,function(a,b=!1){return a.length?a.map(a=>{var c;let d,e=b?` \xb7 ${c=a.lastSeenAt,(d=Math.floor((Date.now()-(0,h.toDate)(c).getTime())/864e5))>=365?`${Math.floor(d/365)}y`:d>=30?`${Math.floor(d/30)}mo`:`${Math.max(d,0)}d`}`:"";return`- ${a.path} — ${a.description?.trim()} (${a.factCount})${e}`}).join("\n"):"(nothing saved yet)"},"nowLine",0,m,"reachNames",0,function(a,b){let c=b.map(a=>a.server===d.STUDIO_SERVER?o[a.name]??a.name:a.server);return[...new Set([...a.map(a=>a.name),...c])].join(", ")},"recentCallLines",0,function(a,b){let c=[],f=0;a:for(let h=a.length-1;h>=0;h--){let i=a[h];for(let a=i.turns.length-1;a>=0;a--){let h=function(a,b){if("tool"!==a.role)return`${"user"===a.role?"user":"you"}: ${a.text}`;let c=(0,g.searchOf)(a.tool,a.text);if(c){let b=[...new Set(c.sources.flatMap(a=>(0,k.hostOf)(a.url)??[]))];return`you → ${a.tool} "${(0,k.clip)(c.query??"",d.PROMPT_LINE.toolArgs)}"${b.length?` — ${b.join(", ")}`:""}`}let f=`you → ${a.tool??"tool"} ${(0,k.clip)(a.text,d.PROMPT_LINE.toolArgs)}`;if(a.tool!==e.TOOL_NAMES.thread_start)return f;let h=(0,g.startedLabel)(a.tool,a.text),i=h?b.jobs?.find(a=>a.label===h):void 0;if(!i)return f;let j=i.outcome?`: ${(0,k.clip)(i.outcome,d.PROMPT_LINE.jobOutcome)}`:"";return`you → ${a.tool} "${i.label}" (${i.id}) — ${i.status}${j}`}(i.turns[a],i),l=(0,j.estimateTokens)(h)+3;if(f+l>b&&c.length)break a;f+=l,c.push({call:i,line:h})}}c.reverse();let h=[],i=null;for(let{call:a,line:b}of c)a!==i&&(i=a,h.push(`### ${n(a.startedAt)}`)),h.push(b);return h.join("\n")},"saidStamp",0,a=>(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm"),"skillLines",0,(a,b={})=>a.map(a=>{var c;let e,g;return`- **${a.name}**: ${b.short?(c=a.description,e=d.PROMPT_LINE.skill,(g=(0,f.firstSentence)(c)).length>e?`${g.slice(0,e).trim()}…`:g):a.description}`}).join("\n"),"styleLines",0,a=>a?.trim()?`## Who they want you to be
|
|
76
80
|
|
|
77
81
|
Their own words, on top of the character above: how you talk to them, how much to say, what to leave out. Where they differ from anything above, theirs wins.
|
|
78
82
|
|
|
79
83
|
${a.trim()}`:"","thursdayIdentity",0,(a=new Date)=>`You are Thursday, this user's own: their friend first, and their assistant second — someone they call because they want to talk to you, who can also get whatever they need done in the background. Named after Friday, the AI in *Iron Man*: a name, not a day of the week. ${m(a)}
|
|
80
84
|
|
|
81
|
-
What they tell you is kept, so you know them better over time.`,"tidying",0,a=>({crowded:a.reduce((a,b)=>a+b.factCount,0)>d.MEMORY_LIMITS.facts,heavy:a.filter(a=>a.factCount>d.MEMORY_LIMITS.factsPerNote)})])},978876,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(938934),h=a.i(762008),i=a.i(446957),j=a.i(109955),k=a.i(344853),l=a.i(182248),m=b([k]);[k]=m.then?(await m)():m;let o=e.string().describe("Its label or id."),p={description:"Start a new thread: hand work to a bot. Returns a receipt at once; the work runs in the background and its updates reach the conversation on their own.",parameters:e.object({bot:e.string().describe("A name from the bot list."),request:e.string().describe("The whole of the work. The bot cannot hear the call, so everything it needs goes here — names, paths, what the user actually asked for — in their own language and their own words: it is the only language the bot has, and whatever it writes comes back to them. **Their request, never your reading of it**: a condition, a caution or a smaller goal they did not say is how work comes back as the wrong thing. When their words leave a real choice open, ask them on the call and put the answer here."),label:e.string().describe("Two or three words naming the thread, in the user's language. Used on screen and said out loud.")})},q={description:"Say something to a thread that exists. Its bot reads it with everything the thread already holds.",parameters:e.object({thread:o,words:e.string().describe("What to tell its bot, in the user's language and words.")})},r={description:`Answer a question a bot asked the user. Only for a question that is waiting; anything else said to a thread is \`${h.TOOL_NAMES.thread_tell}\`.`,parameters:e.object({thread:o,bot:e.string().describe("The bot that asked."),answer:e.string().describe("The user's answer, in their words.")})},s={description:`Read threads as they are now. "all" lists up to ${f.THREAD_STATUS_LIMIT}, running and waiting work before recent endings; a label or an id reads that one whole, with its result and any question waiting.`,parameters:e.object({thread:e.string().describe('"all", or one thread by its label or its id.')})},t={description:"Stop a thread
|
|
85
|
+
What they tell you is kept, so you know them better over time.`,"tidying",0,a=>({crowded:a.reduce((a,b)=>a+b.factCount,0)>d.MEMORY_LIMITS.facts,heavy:a.filter(a=>a.factCount>d.MEMORY_LIMITS.factsPerNote)})])},978876,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(938934),h=a.i(762008),i=a.i(446957),j=a.i(109955),k=a.i(344853),l=a.i(182248),m=b([k]);[k]=m.then?(await m)():m;let o=e.string().describe("Its label or id."),p={description:"Start a new thread: hand work to a bot. Returns a receipt at once; the work runs in the background and its updates reach the conversation on their own.",parameters:e.object({bot:e.string().describe("A name from the bot list."),request:e.string().describe("The whole of the work. The bot cannot hear the call, so everything it needs goes here — names, paths, what the user actually asked for — in their own language and their own words: it is the only language the bot has, and whatever it writes comes back to them. **Their request, never your reading of it**: a condition, a caution or a smaller goal they did not say is how work comes back as the wrong thing. When their words leave a real choice open, ask them on the call and put the answer here."),label:e.string().describe("Two or three words naming the thread, in the user's language. Used on screen and said out loud.")})},q={description:"Say something to a thread that exists. Its bot reads it with everything the thread already holds.",parameters:e.object({thread:o,words:e.string().describe("What to tell its bot, in the user's language and words.")})},r={description:`Answer a question a bot asked the user. Only for a question that is waiting; anything else said to a thread is \`${h.TOOL_NAMES.thread_tell}\`.`,parameters:e.object({thread:o,bot:e.string().describe("The bot that asked."),answer:e.string().describe("The user's answer, in their words.")})},s={description:`Read threads as they are now. "all" lists up to ${f.THREAD_STATUS_LIMIT}, running and waiting work before recent endings; a label or an id reads that one whole, with its result and any question waiting.`,parameters:e.object({thread:e.string().describe('"all", or one thread by its label or its id.')})},t={description:"Stop a thread now: its bot stops where it is. The thread is kept, and saying more to it later carries it on.",parameters:e.object({thread:o})},u={description:"Put a thread in front of the user on their screen: the file it made, or the thread itself when it made none. Showing it also counts as them having seen its result.",parameters:e.object({thread:o})},v={description:"Mark a thread's result as seen by the user. It leaves the work waiting on them.",parameters:e.object({thread:o})},w={description:"Send a message to another bot or to Thursday; the delivery receipt comes back immediately. A bot answers with the final text of its turn, which reaches you later as a new message. Mark a question for Thursday to request user input; ordinary messages to Thursday are notifications and need no answer.",parameters:j.RoomMessageSchema.extend({kind:j.RoomMessageSchema.shape.kind.describe("Use question only when Thursday must obtain an answer from the user: it ends your turn, and you continue when the answer arrives. Use message for bot collaboration, progress updates and reports."),options:j.RoomMessageSchema.shape.options.describe("With a question, offer concise answer choices when useful. Omit for an open-ended question; the user can always type their own answer."),to:e.string().trim().min(1).describe("A bot from the roster other than the one you are answering, or Thursday to reach the user."),text:e.string().trim().min(1).describe("Write the message and include the context the recipient needs. A question to Thursday is put to the user word for word, on screen, on their phone and read aloud: write it to them."),why:e.string().trim().min(1).describe("What you need from them, in a few words, written for the user to read: they see who was brought in and what for.")})},x={description:"Open one of your other threads whole: what you were asked there and your last words in full.",parameters:e.object({id:e.string().describe("The id in brackets on its line under Your other threads.")})};async function n(a,b){let c=await (0,k.listBotWork)(a,b),e=[...c.open,...c.recent];if(!e.some(a=>a.cut))return{};let j=new Set;return{[h.TOOL_NAMES.thread_recall]:(0,d.tool)({description:x.description,inputSchema:x.parameters,execute:async({id:b})=>{let c=b.trim().replace(/^\[|\]$/g,"").toLowerCase(),d=e.find(a=>c.length>=4&&(a.id.startsWith(c)||a.label.toLowerCase()===c));if(!d)return`No thread "${b}" on your list. The ids there: ${e.filter(a=>a.cut).map(a=>(0,i.workHandle)(a.id)).join(", ")}.`;if(!d.cut)return"Its line already shows all of it.";if(j.has(d.id))return"Already opened above, this turn.";if(j.size>=f.BOT_WORK.reads)return`${f.BOT_WORK.reads} threads are open already this turn. Carry on with what you have.`;j.add(d.id);let h=await (0,k.readBotAsk)(a,d),m=d.said??"";return[(0,g.botWorkHead)(d,a),h?`You were asked: ${(0,l.clip)(h,f.BOT_WORK.asked)}`:"",`Your last words there:
|
|
82
86
|
${m.length>f.BOT_WORK.readChars?`${m.slice(0,f.BOT_WORK.readChars)}
|
|
83
87
|
[Cut here; the files it names hold the rest.]`:m}`].filter(Boolean).join("\n\n")}})}}a.s(["createThreadRecallTool",0,n,"sendMessageSpec",0,w,"threadAnswerSpec",0,r,"threadCancelSpec",0,t,"threadSeenSpec",0,v,"threadShowSpec",0,u,"threadStartSpec",0,p,"threadStatusSpec",0,s,"threadTellSpec",0,q]),c()}catch(a){c(a)}},!1),375827,a=>{"use strict";var b=a.i(527990),c=a.i(794219),d=a.i(762008);let e=Object.keys({A:[".##.","#..#","####","#..#","#..#"],B:["###.","#..#","###.","#..#","###."],C:[".###","#...","#...","#...",".###"],D:["###.","#..#","#..#","#..#","###."],E:["####","#...","###.","#...","####"],F:["####","#...","###.","#...","#..."],G:[".###","#...","#.##","#..#",".###"],H:["#..#","#..#","####","#..#","#..#"],I:["###",".#.",".#.",".#.","###"],J:["..##","...#","...#","#..#",".##."],K:["#..#","#.#.","##..","#.#.","#..#"],L:["#...","#...","#...","#...","####"],M:["#...#","##.##","#.#.#","#...#","#...#"],N:["#..#","##.#","#.##","#..#","#..#"],O:[".##.","#..#","#..#","#..#",".##."],P:["###.","#..#","###.","#...","#..."],Q:[".##.","#..#","#..#","#.#.",".#.#"],R:["###.","#..#","###.","#.#.","#..#"],S:[".###","#...",".##.","...#","###."],T:["###",".#.",".#.",".#.",".#."],U:["#..#","#..#","#..#","#..#",".##."],V:["#...#","#...#",".#.#.",".#.#.","..#.."],W:["#...#","#...#","#.#.#","##.##","#...#"],X:["#..#","#..#",".##.","#..#","#..#"],Y:["#.#","#.#",".#.",".#.",".#."],Z:["####","...#",".##.","#...","####"],0:[".##.","#.##","#..#","##.#",".##."],1:[".#.","##.",".#.",".#.","###"],2:["###.","...#",".##.","#...","####"],3:["###.","...#",".##.","...#","###."],4:["#..#","#..#","####","...#","...#"],5:["####","#...","###.","...#","###."],6:[".##.","#...","###.","#..#",".##."],7:["####","...#","..#.",".#..",".#.."],8:[".##.","#..#",".##.","#..#",".##."],9:[".##.","#..#",".###","...#",".##."],"!":["#","#","#",".","#"],"?":["###.","...#",".##.","....",".#.."],".":[".",".",".",".","#"],",":["..","..","..",".#","#."],"'":["#","#",".",".","."],"-":["...","...","###","...","..."],"+":["...",".#.","###",".#.","..."],":":[".","#",".","#","."],"(":[".#","#.","#.","#.",".#"],")":["#.",".#",".#",".#","#."],"<":["..#",".#.","#..",".#.","..#"],">":["#..",".#.","..#",".#.","#.."],"^":[".#.","#.#","...","...","..."],"~":["....",".#.#","#.#.","....","...."],"♥":[".#.#.","#####","#####",".###.","..#.."]," ":["..","..","..","..",".."]}).filter(a=>!/^[A-Z0-9 ]$/.test(a)),f={description:`End the call.
|
|
84
88
|
|
|
85
89
|
The line stays open until this runs, and drops once the goodbye being said is over.`,parameters:c.object({})},g=(0,b.tool)({description:f.description,inputSchema:f.parameters}),h={description:"Show a short word on your face for a few seconds.",parameters:c.object({text:c.string().describe(`Up to 8 characters: A-Z, 0-9, space and ${e.join(" ")}.`)})},i=(0,b.tool)({description:h.description,inputSchema:h.parameters});a.s(["callTools",0,function(){return{[d.TOOL_NAMES.end_call]:g,[d.TOOL_NAMES.emote]:i}}],375827)},127507,a=>{"use strict";var b=a.i(874533),c=a.i(912714),d=a.i(660526),e=a.i(750227),f=a.i(812057),g=a.i(527990),h=a.i(723885),i=a.i(569572),j=a.i(762008),k=a.i(684321),l=a.i(821415);let m=(0,e.join)(i.APP_DIR,i.PATHS.skills.default,"artifact",i.PATHS.skills.runtime,"deck","deck.mjs"),n=a=>h.default.string().trim().max(a),o=n(100).nullish().describe("A source or a date along the foot of the slide."),p=n(1500).nullish().describe("What the presenter says over it, as speech. Never shown."),q=h.default.object({layout:h.default.literal("cover"),title:n(110).describe("The deck's subject, as its title."),eyebrow:n(40).nullish().describe("A word or two above the title."),subtitle:n(180).nullish().describe("One line under the title."),footer:o,notes:p}),r=h.default.object({layout:h.default.literal("statement"),title:n(120).describe("The one claim, as a sentence."),subtitle:n(140).nullish().describe("One line under it."),notes:p}),s=h.default.object({layout:h.default.literal("cards"),title:n(90).describe("The point the cards make together."),cards:h.default.array(h.default.object({title:n(60).describe("Its point."),text:n(160).nullish().describe("One line under it.")})).min(2).max(4).describe("Two to four, side by side and numbered."),footer:o,notes:p}),t=h.default.object({layout:h.default.literal("number"),value:n(10).describe("The figure as it reads: 1.4M, 62%, £2,900. Only one you were given."),label:n(80).nullish().describe("What it counts, above it."),subtitle:n(160).nullish().describe("What it means or is compared with, under it."),footer:o,notes:p}),u=h.default.object({layout:h.default.literal("table"),title:n(90).describe("What the comparison shows."),columns:h.default.array(n(40)).min(2).max(5).describe("The header row. The first column names the rows; its header may be blank."),rows:h.default.array(h.default.array(n(60))).min(1).max(6).describe("Up to six, a cell for each column."),stress:h.default.number().int().min(0).max(4).nullish().describe("Which column, counted from 0, to set in the accent: the one the slide argues for."),footer:o,notes:p}),v=h.default.object({layout:h.default.literal("quote"),quote:n(280).describe("Someone's own words, exactly as you were given them. Never made up."),who:n(60).describe("Who said it."),role:n(80).nullish().describe("Their role, place or date."),notes:p}),w=h.default.object({layout:h.default.literal("image"),title:n(90).describe("The heading beside the picture."),subtitle:n(280).nullish().describe("A line or two under it."),image:n(500).describe("Workspace path of a png, jpg, webp, gif or svg. It is copied beside the deck."),alt:n(160).describe("What it shows, for someone who cannot see it."),fit:h.default.enum(["fill","whole"]).nullish().describe("fill crops a photo to its box; whole shows a chart or screenshot uncropped. Null for fill."),footer:o,notes:p}),x=h.default.object({layout:h.default.literal("close"),title:n(120).describe("The sentence to repeat to someone who was not there."),steps:h.default.array(h.default.object({label:n(24).describe("A word or two: Next, Owner, By."),text:n(120).describe("What it is.")})).max(3).nullish().describe("Up to three next steps."),notes:p}),y=h.default.object({layout:h.default.literal("timeline"),title:n(90).describe("What the dates show together."),steps:h.default.array(h.default.object({when:n(24).describe("When, as you were given it: a date, a week, a phase."),title:n(60).describe("What happens then."),text:n(120).nullish().describe("One line under it.")})).min(2).max(5).describe("Two to five, in order, along one line."),footer:o,notes:p}),z=h.default.object({layout:h.default.literal("compare"),title:n(90).describe("What changes between the two, as a sentence."),sides:h.default.array(h.default.object({label:n(30).describe("Which side it is: Now, After, Option A."),points:h.default.array(n(90)).min(1).max(4)})).length(2).describe("The two, left then right; the right is set in the accent: the side the slide argues for."),footer:o,notes:p}),A=h.default.object({layout:h.default.literal("stats"),title:n(90).describe("What the figures say together."),stats:h.default.array(h.default.object({value:n(12).describe("The figure as it reads: 1.4M, 62%, 6 hours. Only one you were given."),label:n(80).describe("What it counts, under it.")})).min(2).max(4).describe("Two to four figures side by side."),footer:o,notes:p}),B=h.default.discriminatedUnion("layout",[q,r,s,t,u,v,w,y,z,A,x]),C=h.default.object({deck:n(300).describe("A name for a new deck, or the name or workspace path of one to change. A deck another bot made is reached by its path."),title:n(90).describe("The deck's title, shown in its head."),theme:h.default.enum(["forest","sea","clay","ink"]).nullish().describe("forest (deep green on paper, serif headings), sea (blue, sans), clay (terracotta on warm paper, serif) or ink (gold on near-black, sans). Null keeps the deck's own; a new one starts in forest."),revision:h.default.string().nullish().describe("What the last call on this deck answered with. Null for a new deck."),slides:h.default.array(B).min(1).max(i.DECK.slides).describe("Every slide in order: the whole deck, each time. Someone who reads only the titles follows the argument; one idea a slide.")}),D=/^[\p{L}\p{N}][\p{L}\p{N}_-]{0,79}$/u,E=/^(slide-\d+|slides)\.png$/i;class F extends Error{}function G(a){let b=a.replace(/[^\p{L}\p{N}_-]+/gu,"-").replace(/^[-_]+|-+$/g,"").slice(0,80);if(!D.test(b))throw new F(`"${a}" is not a deck name: use letters, numbers, - and _.`);return b}async function H(a,b){let d=(0,l.botArtifacts)(b);if(!a.includes("/")&&!a.endsWith(".html")){let b=G(a);return`${d}/${b}/${b}.html`}let f=await (0,l.insideWorkspace)(a);if(!f)throw new F(`${a} is outside the workspace. Give a deck's path in it.`);let g=await (0,c.realpath)(l.WORKSPACE).catch(()=>l.WORKSPACE),h=await (0,c.stat)(f).catch(()=>null),i=h?.isDirectory()?(0,e.join)(f,`${(0,e.basename)(f)}.html`):f;if((await (0,c.stat)(i).catch(()=>null))?.isFile())return(0,e.relative)(g,i);let j=await (0,l.insideWorkspace)(d);if(!j||!f.startsWith(`${j}${e.sep}`))throw new F(`There is no deck at ${a}. A new deck is made in your own folder: give it a name.`);let k=G((0,e.basename)(f,".html"));return(0,e.relative)(g,(0,e.join)((0,e.dirname)(f),k,`${k}.html`))}async function I(a,b,d){let f=new Map,g=[];for(let[h,i]of a.entries()){if("table"===i.layout){let a=i.rows.findIndex(a=>a.length>i.columns.length);if(-1!==a)throw new F(`Slide ${h+1}: row ${a+1} has ${i.rows[a].length} cells, and there are ${i.columns.length} columns.`);g.push({...i,rows:i.rows.map(a=>i.columns.map((b,c)=>a[c]??""))});continue}if("image"!==i.layout){g.push(i);continue}let a=b.resolve(d),j=(0,e.join)(a,i.image),l=!i.image.includes("/")&&await (0,c.stat)(j).catch(()=>null)?j:b.resolve(i.image);if("image"!==(0,k.viewKindOf)(l))throw new F(`Slide ${h+1}: ${i.image} is not a picture. Give a png, jpg, webp, gif or svg.`);if(!(await (0,c.stat)(l).catch(()=>null))?.isFile())throw new F(`Slide ${h+1}: there is no file at ${i.image}. Give its path from the workspace root, as \`ls\` shows it.`);let m=f.get(l);m||(m=(0,e.dirname)(l)===a?(0,e.basename)(l):function(a,b){let c=(0,e.extname)(a),d=(0,e.basename)(a,c),f=E.test(a)?`picture-${d}`:d,g=`${f}${c}`;for(let a=2;b.has(g);a++)g=`${f}-${a}${c}`;return g}((0,e.basename)(l),new Set(f.values())),f.set(l,m),(0,e.dirname)(l)!==a&&(await (0,c.mkdir)(a,{recursive:!0}),await (0,c.copyFile)(l,(0,e.join)(a,m)))),g.push({...i,image:m})}return g}let J=(0,f.promisify)(b.execFile);async function K(a,b,f,g,h){let i=await (0,c.mkdtemp)((0,e.join)((0,d.tmpdir)(),"thursday-deck-"));try{let d=(0,e.join)(i,"deck.json");await (0,c.writeFile)(d,JSON.stringify(b));let j=[m,"put",(0,e.join)(l.WORKSPACE,a),d];f&&j.push("--revision",f);let k=await J(process.execPath,j,{env:{NODE_ENV:"production",PATH:process.env.PATH??"",THURSDAY_BOT:g,...h?{THURSDAY_BOT_MARK:h}:{}},maxBuffer:0x1000000}).catch(a=>{if(3===a.code&&a.stdout)return{stdout:a.stdout};throw new F(a.stderr?.trim().split("\n").at(-1)||"The deck could not be written.")});return JSON.parse(k.stdout.trim().split("\n").at(-1)??"")}finally{await (0,c.rm)(i,{recursive:!0,force:!0})}}async function L(a,b,c,d){let f=await a.exec('node "$DECK_SCRIPT" shots "$DECK_FILE"',{env:{...c,DECK_SCRIPT:m,DECK_FILE:(0,e.join)(l.WORKSPACE,b)},timeoutMs:i.DECK.shotsMs,signal:d});if(0!==f.exitCode)return{failed:f.stderr.trim().split("\n").at(-1)||"no pictures were made"};let g=JSON.parse(f.stdout.trim().split("\n").at(-1)??"{}");return{pictures:g.pictures.map(a=>(0,e.relative)(l.WORKSPACE,a)),sheet:g.sheet?(0,e.relative)(l.WORKSPACE,g.sheet):null,cut:g.cut}}a.s(["createDeckTools",0,(a,b,d,f)=>({[j.TOOL_NAMES.make_deck]:(0,g.tool)({description:"Make a slide deck, or change one: each slide a layout whose fields you fill, drawn and fitted by the app into one HTML file that opens offline, presents full screen and prints a slide a page, with a picture of every slide beside it.",inputSchema:C,execute:async(c,{abortSignal:f})=>{try{let g,h=await H(c.deck,b),i=await I(c.slides,a,(0,e.dirname)(h)),k=await K(h,{title:c.title,theme:c.theme??null,slides:i},c.revision?.trim()??"",b,d.THURSDAY_BOT_MARK);if("changed"in k){if(!k.deck)return`${h} is not a deck made of slides, so it cannot be changed here. Give the deck another name.`;let a=c.revision?.trim()?`${h} has changed since that revision — edited in the app, or by another job`:`there is already a deck at ${h}`;return{deck:h,revision:k.revision,note:`Nothing was written: ${a}. This is the deck as it stands. To change it, make your change on these slides and call \`${j.TOOL_NAMES.make_deck}\` again with revision ${k.revision} and the whole deck; for a deck of its own, give a new name.`,current:k.deck}}let l=`${i.length} slide${1===i.length?"":"s"}, revision ${k.revision}`,m=await L(a,h,d,f);if("failed"in m)return`${h}
|
|
86
90
|
${l}. The pictures of its slides could not be made (${m.failed}), so nothing checked that every slide fits. Hand back the deck's path.`;let n=`call \`${j.TOOL_NAMES.make_deck}\` again with revision ${k.revision} and the whole deck`,o=m.sheet?`${(0,e.basename)(m.sheet)} holds every slide, numbered, and each is on its own beside it from slide-01.png`:"Its pictures are beside it, slide-01.png on";return[h,m.sheet??m.pictures[0]??"",m.cut.length?`${l}. ${g=m.cut,1===g.length?`Slide ${g[0]} does`:`Slides ${g.slice(0,-1).join(", ")} and ${g.at(-1)} do`} not fit even with the type at its smallest: say less there, then ${n}. ${o}.`:`${l}. Every slide fits. ${o}. Hand back the deck's path; to change it, ${n}.`].filter(Boolean).join("\n")}catch(a){if(a instanceof F)return a.message;throw a}},toModelOutput:async({output:a})=>{if("string"!=typeof a)return{type:"json",value:a};let b=a.split("\n")[1]??"";if(!f||!b.endsWith(".png"))return{type:"text",value:a};let d=await (0,l.insideWorkspace)(b),e=d?await (0,c.readFile)(d).catch(()=>null):null;return!e||e.byteLength>i.LOOK.maxBytes?{type:"text",value:a}:{type:"content",value:[{type:"text",text:`${a}
|
|
87
91
|
|
|
88
|
-
${b}, as an image:`},{type:"file",mediaType:"image/png",data:{type:"data",data:e.toString("base64")}}]}}})})])},467650,a=>{"use strict";var b=a.i(912714),c=a.i(527990),d=a.i(723885),e=a.i(569572),f=a.i(762008),g=a.i(684321),h=a.i(821415);a.s(["createLookTool",0,function(){return{[f.TOOL_NAMES.look_at]:(0,c.tool)({description:"See an image file yourself: a screenshot you took, a picture the user handed over, a chart you made. For what a picture shows — text files are read in the shell.",inputSchema:d.default.object({path:d.default.string().describe("Workspace-relative path to a png, jpg, webp or gif.")}),execute:async({path:a})=>{let c=await (0,h.insideWorkspace)(a.trim()),d=c?await (0,b.stat)(c).catch(()=>null):null;return c&&d?.isFile()?"image"!==(0,g.viewKindOf)(a)?`${a} is not an image. Read it in the shell instead.`:d.size>e.LOOK.maxBytes?`${a} is ${Math.ceil(d.size/1024/1024)} MB, over the ${e.LOOK.maxBytes/1024/1024} MB one look takes. Make a smaller copy in the shell first (on a Mac: sips -Z 1600 in.png --out out.png), then look at that.`:{path:a.trim(),mediaType:(0,g.mimeOf)(a)}:`There is no file at ${a}. Give the path from the workspace root, as \`ls\` shows it.`},toModelOutput:async({output:a})=>{if("string"==typeof a)return{type:"text",value:a};let c=await (0,h.insideWorkspace)(a.path),d=c?await (0,b.readFile)(c).catch(()=>null):null;return d?{type:"content",value:[{type:"text",text:`${a.path}, as an image:`},{type:"file",mediaType:a.mediaType,data:{type:"data",data:d.toString("base64")}}]}:{type:"text",value:`${a.path} is no longer there.`}}})}}])},138902,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(762008),h=a.i(947950),i=a.i(821415),j=a.i(644468),k=b([h,j]);[h,j]=k.then?(await k)():k;let n={[g.TOOL_NAMES.tool_search]:{description:`Return the description and exact inputSchema of tools on a connected server, so they can be called with \`${g.TOOL_NAMES.tool_call}\`.`,parameters:e.object({server:e.string().describe("A server name, exactly as the Connected tools section writes it."),tools:e.string().array().describe(`Tool names listed under that server. Only the ones you may actually call — schemas are large, and at most ${f.TOOL_SEARCH_SCHEMAS} come back.`)})},[g.TOOL_NAMES.tool_call]:{description:`Run one tool whose definition came back from \`${g.TOOL_NAMES.tool_search}\`.`,parameters:e.object({server:e.string().describe("The server the tool lives on."),tool:e.string().describe("Its name, as search returned it."),args:e.looseObject({}).nullish().describe("Arguments matching the inputSchema search returned — do not guess. Null when it takes none."),description:e.string().nullish().describe("One short line for the user: what this call is for. Shown on their screen while it runs.")})}},o=(a,b)=>`${a.replace(/[^a-zA-Z0-9]+/g,"_")}__${b.replace(/[^a-zA-Z0-9_-]+/g,"_")}`.slice(0,64);async function l(a,b){let[c,e]=await Promise.all([(0,j.listConnectedToolNames)(),(0,h.findPinnedTools)(a)]),f={},g=(0,i.botArtifacts)(a);for(let a of e){let c=o(a.server,a.name);f[c]||(f[c]=(0,d.tool)({description:a.description??`${a.name} on the ${a.server} server.`,inputSchema:(0,d.jsonSchema)(a.inputSchema??{type:"object",properties:{}}),execute:(c,{abortSignal:d})=>(0,j.callConnectedTool)(b,a.server,a.name,c??void 0,{artifacts:g,abortSignal:d})}))}return c.length>e.length&&Object.assign(f,p(b,g)),f}async function m(a){let b=(await (0,j.listConnectedToolNames)(a)).map(a=>a.name);if(b.length)return`Tools on "${a}": ${b.join(", ")}.`;let c=await (0,j.listConnectedServerNames)();return c.length?`There is no server called "${a}". Connected: ${c.join(", ")}.`:"Nothing is connected."}let p=(a,b)=>({[g.TOOL_NAMES.tool_search]:(0,d.tool)({description:n[g.TOOL_NAMES.tool_search].description,inputSchema:n[g.TOOL_NAMES.tool_search].parameters,execute:async({server:a,tools:b})=>{let c=[...new Set(b.map(a=>a.trim()).filter(Boolean))],d=c.slice(0,f.TOOL_SEARCH_SCHEMAS),e=await (0,j.findConnectedSchemas)(a.trim(),d);if(!e.length)return{tools:[],note:await m(a)};let g=d.filter(a=>!e.some(b=>b.name===a)),h=c.slice(f.TOOL_SEARCH_SCHEMAS),i=[g.length?`Not on "${a}": ${g.join(", ")}.`:"",h.length?`Only ${f.TOOL_SEARCH_SCHEMAS} at a time — ask again for: ${h.join(", ")}.`:""].filter(Boolean);return{tools:e,...i.length?{note:i.join(" ")}:{}}}}),[g.TOOL_NAMES.tool_call]:(0,d.tool)({description:n[g.TOOL_NAMES.tool_call].description,inputSchema:n[g.TOOL_NAMES.tool_call].parameters,execute:async({server:c,tool:d,args:e},{abortSignal:f})=>(await (0,j.listConnectedToolNames)(c.trim())).some(a=>a.name===d.trim())?(0,j.callConnectedTool)(a,c.trim(),d.trim(),e??void 0,{artifacts:b,abortSignal:f}):{status:"error",text:await m(c)}})});a.s(["createMcpTools",0,l]),c()}catch(a){c(a)}},!1),345846,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(938934),h=a.i(762008),i=a.i(986743),j=a.i(661210),k=b([i]);[i]=k.then?(await k)():k;let l=j.MEMORY_PATHS.map(a=>a.path.endsWith("/")?`${a.path}<name>`:a.path).join(", "),m="Saved. The listing in your instructions is from when this session opened and will not show this until the next one — the note below is current.",n=a=>`Nothing on the listing called ${a}.`,o=a=>({...a,facts:a.facts.map(({saidAt:a,...b})=>a?{...b,said:(0,g.saidStamp)(a)}:b),factCount:a.facts.length}),p=a=>a>f.MEMORY_LIMITS.factsPerNote?` This note now holds ${a} facts, past the ${f.MEMORY_LIMITS.factsPerNote} one note holds well. Ask the user which of it is no longer true and delete what they name.`:"",q=a=>a.length>f.MEMORY_LIMITS.descriptionChars?{note:`That line runs to ${a.length} characters; a note's line is one line, under ${f.MEMORY_LIMITS.descriptionChars}. Say what the note is about — the facts inside say the rest.`}:null,r=e.string().describe("Exactly as the listing writes it — the path."),s=e.string().describe('One statement that stands on its own later — a date as a date, never "next week".');a.s(["createMemoryTools",0,(a,b=null,{countReads:c=!0}={})=>({[h.TOOL_NAMES.memory_recall]:(0,d.tool)({description:"Open one note from the listing, whole.",inputSchema:e.object({path:r}),execute:async({path:a})=>{let{notes:b}=await (0,i.readNotes)([a],{touch:c}),d=b[0];if(!d)return{note:n(a.trim())};let e=p(d.facts.length);return e?{...o(d),note:e.trim()}:o(d)}}),[h.TOOL_NAMES.memory_create]:(0,d.tool)({description:"Start a note for a subject that is not on the listing: its path, the line it is listed by, and its first facts.",inputSchema:e.object({path:e.string().describe(`A new path following the listing's convention — one of ${l} — for the person, project or topic the facts are about. A fact goes under the one note it is about; other notes name it rather than repeat it.`),description:e.string().describe("One line saying what this note is about, with the names the user calls it by, so the listing alone tells whether to open it. What it is about — never a list of what is inside."),facts:e.object({text:s}).array().min(1).describe("What to keep under it. Send everything that came up at once: one call is one pause in the conversation, three calls are three.")}),execute:async({path:c,description:d,facts:e})=>{let f=c.trim(),g=d.trim();if(!(0,j.isMemoryPath)(f))return{note:`Nothing was saved: "${f}" is not a path this listing can carry. Write it again under one of ${l}.`};if((0,j.isAlwaysListed)(f))return{note:`${f} is always on the listing: \`${h.TOOL_NAMES.memory_remember}\` adds to it.`};let k=q(g);if(k)return k;let n=await (0,i.createNoteWithFacts)(f,g,e,a,b);if(!n)return{note:`${f} is already on the listing: \`${h.TOOL_NAMES.memory_remember}\` adds to it, \`${h.TOOL_NAMES.memory_describe}\` changes its line.`};let r=o(n);return{...r,note:`${m}${p(r.factCount)}`}}}),[h.TOOL_NAMES.memory_remember]:(0,d.tool)({description:"Write facts under a note that is on the listing.",inputSchema:e.object({path:r,facts:e.object({text:s,replaces:e.number().int().nullish().describe(`The id of the fact this replaces — from this note as handed back here or by \`${h.TOOL_NAMES.memory_recall}\`. Null if this is new. A fact that stopped being true is replaced rather than deleted, and so is a note saying the same thing twice: replacing keeps what changed on the record, deleting does not.`)}).array().min(1).describe("What to write under this note. Send everything that came up at once: one call is one pause in the conversation, three calls are three.")}),execute:async({path:c,facts:d})=>{let e=c.trim(),f=await (0,i.writeFacts)(e,d,a,b);if(!f)return{note:`${n(e)} A subject that is not on the listing gets a note of its own: \`${h.TOOL_NAMES.memory_create}\`, with its line.`};let g=o(f);return{...g,note:`${m}${p(g.factCount)}`}}}),[h.TOOL_NAMES.memory_describe]:(0,d.tool)({description:"Change the line a note is listed by, when it no longer says what the note is about.",inputSchema:e.object({path:r,description:e.string().describe("The new line, whole: what this note is about, with the names the user calls it by. Never a list of what is inside.")}),execute:async({path:a,description:b})=>{let c=a.trim(),d=b.trim();if((0,j.isAlwaysListed)(c))return{note:`${j.MEMORY_ALWAYS_LISTED.join(" and ")} keep their own line; it is not yours to change.`};let e=q(d);return e||(await (0,i.describeNote)(c,d)?{path:c,description:d,note:"Renamed. The listing in your instructions is from when this session opened and still shows the old line until the next one."}:{note:n(c)})}}),[h.TOOL_NAMES.memory_forget]:(0,d.tool)({description:"Delete facts for good.",inputSchema:e.object({factIds:e.number().int().array().min(1).describe("The ids that came with the facts when their notes were opened — every one to delete, in one call.")}),execute:async({factIds:a})=>{let b=[],c=[],d=new Set;for(let e of new Set(a)){let a=await (0,i.forgetFactById)(e);if(!a){b.push(e);continue}a.noteGone?(d.delete(a.path),c.push(a.path)):d.add(a.path)}if(!c.length&&!d.size)return{note:`No fact with id ${b.join(", ")}. Nothing was deleted.`};let e=["Deleted for good. The listing in your instructions is from when this session opened and still shows it that way until the next one.",1===c.length?`That was the last fact under ${c[0]}, so the note went with it.`:c.length?`That was the last of ${c.join(", ")}, so those notes went with them.`:"",b.length?`No fact with id ${b.join(", ")}, so those were skipped.`:""].filter(Boolean).join(" ");if(!d.size)return{note:e};let{notes:f}=await (0,i.readNotes)([...d],{touch:!1});return{notes:f.map(o),note:e}}})})]),c()}catch(a){c(a)}},!1),617594,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(762008),h=a.i(221214),i=a.i(780946),j=a.i(643020),k=a.i(706210),l=a.i(293480),m=a.i(182248),n=b([h,i]);[h,i]=n.then?(await n)():n;let q={description:`Routines: work that starts by itself, each one a bot, the work and a time — once at a moment, a time of day on chosen days, or every few hours. List them, make one, change one, or delete one. Every start opens a thread like one started by hand; its result reaches the conversation the same way. At most ${f.ROUTINE.max} exist.`,parameters:e.object({action:e.enum(["list","create","change","delete"]),routine:e.string().nullish().describe("With change or delete: the routine, by its name or ID."),bot:e.string().nullish().describe("With create: a name from the bot list. With change: a new bot."),label:e.string().nullish().describe("With create: two or three words naming it, in the user's language. It names every thread the routine opens, on screen and out loud."),request:e.string().nullish().describe("With create: the whole of the work, handed to the bot as written every time it starts. Nobody is there then to fill in what is missing, so everything it needs goes here, in the user's own language and words. Their request, never your reading of it."),at:e.string().nullish().describe('Starts once, at this moment, "YYYY-MM-DD HH:MM" in the user\'s own time, then switches itself off. Count "in an hour" or "tomorrow at eight" from **Now**. Give one of `at`, `time` or `everyHours`.'),time:e.string().nullish().describe('Starts at this time of day, 24-hour "HH:MM" in the user\'s own time, on `days`. Give one of `at`, `time` or `everyHours`.'),days:e.array(e.number().int().min(1).max(7)).nullish().describe("With `time`: the days it starts, 1 Monday to 7 Sunday. Omit for every day."),everyHours:e.number().int().nullish().describe(`Starts again this many hours after it last started, ${f.ROUTINE.minHours} at least. Give one of \`at\`, \`time\` or \`everyHours\`.`),enabled:e.boolean().nullish().describe("With change: false switches it off without deleting it, true back on.")})};function o(a){let b=a.runs[0];return{id:a.id,label:a.label,bot:a.bot,when:(0,j.scheduleText)(a.schedule),enabled:a.enabled,...a.enabled?{next:(0,k.whenOf)((0,k.toDate)(a.nextRunAt))}:{},request:(0,m.clip)(a.request,f.PROMPT_LINE.routineRequest),...b?{lastRun:{thread:b.id,status:b.status,at:(0,k.whenOf)((0,k.toDate)(b.updatedAt)),...b.outcome?{outcome:(0,m.clip)(b.outcome,f.PROMPT_LINE.routineOutcome)}:{}}}:{}}}let r=a=>{if((0,l.isPublicError)(a))return a.message;throw a};async function p(a){let b=(await (0,i.listRoutines)()).map(a=>`"${a.label}"`);return b.length?a?`There is no single routine called "${a}". The routines are: ${b.join(", ")}. Call again with one of those, or its ID.`:`Name the routine. The routines are: ${b.join(", ")}.`:"There are no routines yet."}a.s(["createRoutineTools",0,function(){return{[g.TOOL_NAMES.routine]:(0,d.tool)({description:q.description,inputSchema:q.parameters,execute:async a=>{if("list"===a.action)return{routines:(await (0,i.listRoutines)()).map(o)};let b=function(a){if([a.at,a.time,a.everyHours].filter(Boolean).length>1)return"Give one of `at`, `time` or `everyHours`, not two.";let b=a.at?{kind:"once",at:a.at}:a.time?{kind:"daily",time:a.time,days:a.days?.length?a.days:[1,2,3,4,5,6,7]}:a.everyHours?{kind:"every",hours:a.everyHours}:null;if(!b)return null;let c=j.RoutineScheduleSchema.safeParse(b);return c.success?c.data:c.error.issues[0].message}(a);if("string"==typeof b)return b;if("create"===a.action){if(!b)return"Say when it starts: `at`, `time` (with `days`), or `everyHours`.";let c=j.RoutineInputSchema.safeParse({bot:a.bot??"",label:a.label??"",request:a.request??"",schedule:b});if(!c.success)return`${c.error.issues[0].message}. Nothing was made — call again with bot, label, request and when.`;let d=(await (0,h.listJobBots)()).map(a=>a.name);if(!d.some(a=>a.toLowerCase()===c.data.bot.toLowerCase()))return`There is no bot called "${c.data.bot}". The bots are: ${d.join(", ")}. Nothing was made — call again with one of those.`;let e=await (0,i.createRoutine)(c.data).catch(r);if("string"==typeof e)return e;let f=(0,k.whenOf)((0,k.toDate)(e.nextRunAt));return{...o(e),note:"once"===e.schedule.kind?`${e.bot} starts "${e.label}" once, ${f}, and the routine then switches itself off. The start is a thread of its own, and its result reaches the conversation like any thread's.`:`${e.bot} starts "${e.label}" by itself, ${(0,j.scheduleText)(e.schedule)}, first ${f}. Each start is a thread of its own, and its result reaches the conversation like any thread's.`}}let c=a.routine?await (0,i.resolveRoutine)(a.routine):null;if(!c)return await p(a.routine);if("delete"===a.action)return await (0,i.deleteRoutine)(c.id),`"${c.label}" is deleted and starts no more. The threads it already opened stay.`;let d={...a.bot?{bot:a.bot}:{},...a.label?.trim()?{label:a.label.trim()}:{},...a.request?.trim()?{request:a.request.trim()}:{},...b?{schedule:b}:{},..."boolean"==typeof a.enabled?{enabled:a.enabled}:{}};if(!Object.keys(d).length)return"Nothing to change was given: bot, label, request, when, or enabled.";let e=await (0,i.updateRoutine)(c.id,d).catch(r);return"string"==typeof e?e:e?o(e):await p(a.routine)}})}}]),c()}catch(a){c(a)}},!1),622547,a=>a.a(async(b,c)=>{try{var d=a.i(47919),e=a.i(527990),f=a.i(723885),g=a.i(569572),h=a.i(762008),i=a.i(688034),j=a.i(725466),k=a.i(182248),l=b([j]);[j]=l.then?(await l)():l;let p=`Answer the question from the web. Lead with the answer, then
|
|
92
|
+
${b}, as an image:`},{type:"file",mediaType:"image/png",data:{type:"data",data:e.toString("base64")}}]}}})})])},467650,a=>{"use strict";var b=a.i(912714),c=a.i(527990),d=a.i(723885),e=a.i(569572),f=a.i(762008),g=a.i(684321),h=a.i(821415);a.s(["createLookTool",0,function(){return{[f.TOOL_NAMES.look_at]:(0,c.tool)({description:"See an image file yourself: a screenshot you took, a picture the user handed over, a chart you made. For what a picture shows — text files are read in the shell.",inputSchema:d.default.object({path:d.default.string().describe("Workspace-relative path to a png, jpg, webp or gif.")}),execute:async({path:a})=>{let c=await (0,h.insideWorkspace)(a.trim()),d=c?await (0,b.stat)(c).catch(()=>null):null;return c&&d?.isFile()?"image"!==(0,g.viewKindOf)(a)?`${a} is not an image. Read it in the shell instead.`:d.size>e.LOOK.maxBytes?`${a} is ${Math.ceil(d.size/1024/1024)} MB, over the ${e.LOOK.maxBytes/1024/1024} MB one look takes. Make a smaller copy in the shell first (on a Mac: sips -Z 1600 in.png --out out.png), then look at that.`:{path:a.trim(),mediaType:(0,g.mimeOf)(a)}:`There is no file at ${a}. Give the path from the workspace root, as \`ls\` shows it.`},toModelOutput:async({output:a})=>{if("string"==typeof a)return{type:"text",value:a};let c=await (0,h.insideWorkspace)(a.path),d=c?await (0,b.readFile)(c).catch(()=>null):null;return d?{type:"content",value:[{type:"text",text:`${a.path}, as an image:`},{type:"file",mediaType:a.mediaType,data:{type:"data",data:d.toString("base64")}}]}:{type:"text",value:`${a.path} is no longer there.`}}})}}])},138902,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(762008),h=a.i(947950),i=a.i(821415),j=a.i(644468),k=b([h,j]);[h,j]=k.then?(await k)():k;let n={[g.TOOL_NAMES.tool_search]:{description:`Return the description and exact inputSchema of tools on a connected server, so they can be called with \`${g.TOOL_NAMES.tool_call}\`.`,parameters:e.object({server:e.string().describe("A server name, exactly as the Connected tools section writes it."),tools:e.string().array().describe(`Tool names listed under that server. Only the ones you may actually call — schemas are large, and at most ${f.TOOL_SEARCH_SCHEMAS} come back.`)})},[g.TOOL_NAMES.tool_call]:{description:`Run one tool whose definition came back from \`${g.TOOL_NAMES.tool_search}\`.`,parameters:e.object({server:e.string().describe("The server the tool lives on."),tool:e.string().describe("Its name, as search returned it."),args:e.looseObject({}).nullish().describe("Arguments matching the inputSchema search returned — do not guess. Null when it takes none."),description:e.string().nullish().describe("One short line for the user: what this call is for. Shown on their screen while it runs.")})}},o=(a,b)=>`${a.replace(/[^a-zA-Z0-9]+/g,"_")}__${b.replace(/[^a-zA-Z0-9_-]+/g,"_")}`.slice(0,64);async function l(a,b){let[c,e]=await Promise.all([(0,j.listConnectedToolNames)(),(0,h.findPinnedTools)(a)]),f={},g=(0,i.botArtifacts)(a);for(let a of e){let c=o(a.server,a.name);f[c]||(f[c]=(0,d.tool)({description:a.description??`${a.name} on the ${a.server} server.`,inputSchema:(0,d.jsonSchema)(a.inputSchema??{type:"object",properties:{}}),execute:(c,{abortSignal:d})=>(0,j.callConnectedTool)(b,a.server,a.name,c??void 0,{artifacts:g,abortSignal:d})}))}return c.length>e.length&&Object.assign(f,p(b,g)),f}async function m(a){let b=(await (0,j.listConnectedToolNames)(a)).map(a=>a.name);if(b.length)return`Tools on "${a}": ${b.join(", ")}.`;let c=await (0,j.listConnectedServerNames)();return c.length?`There is no server called "${a}". Connected: ${c.join(", ")}.`:"Nothing is connected."}let p=(a,b)=>({[g.TOOL_NAMES.tool_search]:(0,d.tool)({description:n[g.TOOL_NAMES.tool_search].description,inputSchema:n[g.TOOL_NAMES.tool_search].parameters,execute:async({server:a,tools:b})=>{let c=[...new Set(b.map(a=>a.trim()).filter(Boolean))],d=c.slice(0,f.TOOL_SEARCH_SCHEMAS),e=await (0,j.findConnectedSchemas)(a.trim(),d);if(!e.length)return{tools:[],note:await m(a)};let g=d.filter(a=>!e.some(b=>b.name===a)),h=c.slice(f.TOOL_SEARCH_SCHEMAS),i=[g.length?`Not on "${a}": ${g.join(", ")}.`:"",h.length?`Only ${f.TOOL_SEARCH_SCHEMAS} at a time — ask again for: ${h.join(", ")}.`:""].filter(Boolean);return{tools:e,...i.length?{note:i.join(" ")}:{}}}}),[g.TOOL_NAMES.tool_call]:(0,d.tool)({description:n[g.TOOL_NAMES.tool_call].description,inputSchema:n[g.TOOL_NAMES.tool_call].parameters,execute:async({server:c,tool:d,args:e},{abortSignal:f})=>(await (0,j.listConnectedToolNames)(c.trim())).some(a=>a.name===d.trim())?(0,j.callConnectedTool)(a,c.trim(),d.trim(),e??void 0,{artifacts:b,abortSignal:f}):{status:"error",text:await m(c)}})});a.s(["createMcpTools",0,l]),c()}catch(a){c(a)}},!1),345846,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(938934),h=a.i(762008),i=a.i(986743),j=a.i(661210),k=b([i]);[i]=k.then?(await k)():k;let l=j.MEMORY_PATHS.map(a=>a.path.endsWith("/")?`${a.path}<name>`:a.path).join(", "),m="Saved. The listing in your instructions is from when this session opened and will not show this until the next one — the note below is current.",n=a=>`Nothing on the listing called ${a}.`,o=a=>({...a,facts:a.facts.map(({saidAt:a,...b})=>a?{...b,said:(0,g.saidStamp)(a)}:b),factCount:a.facts.length}),p=a=>a>f.MEMORY_LIMITS.factsPerNote?` This note now holds ${a} facts, past the ${f.MEMORY_LIMITS.factsPerNote} one note holds well. Ask the user which of it is no longer true and delete what they name.`:"",q=a=>a.length>f.MEMORY_LIMITS.descriptionChars?{note:`That line runs to ${a.length} characters; a note's line is one line, under ${f.MEMORY_LIMITS.descriptionChars}. Say what the note is about — the facts inside say the rest.`}:null,r=e.string().describe("Exactly as the listing writes it — the path."),s=e.string().describe('One statement that stands on its own later — a date as a date, never "next week".');a.s(["createMemoryTools",0,(a,b=null,{countReads:c=!0,tidies:f=!0}={})=>({[h.TOOL_NAMES.memory_recall]:(0,d.tool)({description:"Open one note from the listing, whole.",inputSchema:e.object({path:r}),execute:async({path:a})=>{let{notes:b}=await (0,i.readNotes)([a],{touch:c}),d=b[0];if(!d)return{note:n(a.trim())};let e=f?p(d.facts.length):"";return e?{...o(d),note:e.trim()}:o(d)}}),[h.TOOL_NAMES.memory_create]:(0,d.tool)({description:"Start a note for a subject that is not on the listing: its path, the line it is listed by, and its first facts.",inputSchema:e.object({path:e.string().describe(`A new path following the listing's convention — one of ${l} — for the person, project or topic the facts are about. A fact goes under the one note it is about; other notes name it rather than repeat it.`),description:e.string().describe("One line saying what this note is about, with the names the user calls it by, so the listing alone tells whether to open it. What it is about — never a list of what is inside."),facts:e.object({text:s}).array().min(1).describe("What to keep under it. Send everything that came up at once: one call is one pause in the conversation, three calls are three.")}),execute:async({path:c,description:d,facts:e})=>{let f=c.trim(),g=d.trim();if(!(0,j.isMemoryPath)(f))return{note:`Nothing was saved: "${f}" is not a path this listing can carry. Write it again under one of ${l}.`};if((0,j.isAlwaysListed)(f))return{note:`${f} is always on the listing: \`${h.TOOL_NAMES.memory_remember}\` adds to it.`};let k=q(g);if(k)return k;let n=await (0,i.createNoteWithFacts)(f,g,e,a,b);if(!n)return{note:`${f} is already on the listing: \`${h.TOOL_NAMES.memory_remember}\` adds to it, \`${h.TOOL_NAMES.memory_describe}\` changes its line.`};let r=o(n);return{...r,note:`${m}${p(r.factCount)}`}}}),[h.TOOL_NAMES.memory_remember]:(0,d.tool)({description:"Write facts under a note that is on the listing.",inputSchema:e.object({path:r,facts:e.object({text:s,replaces:e.number().int().nullish().describe(`The id of the fact this replaces — from this note as handed back here or by \`${h.TOOL_NAMES.memory_recall}\`. Null if this is new. A fact that stopped being true is replaced rather than deleted, and so is a note saying the same thing twice: replacing keeps what changed on the record, deleting does not.`)}).array().min(1).describe("What to write under this note. Send everything that came up at once: one call is one pause in the conversation, three calls are three.")}),execute:async({path:c,facts:d})=>{let e=c.trim(),f=await (0,i.writeFacts)(e,d,a,b);if(!f)return{note:`${n(e)} A subject that is not on the listing gets a note of its own: \`${h.TOOL_NAMES.memory_create}\`, with its line.`};let g=o(f);return{...g,note:`${m}${p(g.factCount)}`}}}),[h.TOOL_NAMES.memory_describe]:(0,d.tool)({description:"Change the line a note is listed by, when it no longer says what the note is about.",inputSchema:e.object({path:r,description:e.string().describe("The new line, whole: what this note is about, with the names the user calls it by. Never a list of what is inside.")}),execute:async({path:a,description:b})=>{let c=a.trim(),d=b.trim();if((0,j.isAlwaysListed)(c))return{note:`${j.MEMORY_ALWAYS_LISTED.join(" and ")} keep their own line; it is not yours to change.`};let e=q(d);return e||(await (0,i.describeNote)(c,d)?{path:c,description:d,note:"Renamed. The listing in your instructions is from when this session opened and still shows the old line until the next one."}:{note:n(c)})}}),[h.TOOL_NAMES.memory_forget]:(0,d.tool)({description:"Delete facts for good.",inputSchema:e.object({factIds:e.number().int().array().min(1).describe("The ids that came with the facts when their notes were opened — every one to delete, in one call.")}),execute:async({factIds:a})=>{let b=[],c=[],d=new Set;for(let e of new Set(a)){let a=await (0,i.forgetFactById)(e);if(!a){b.push(e);continue}a.noteGone?(d.delete(a.path),c.push(a.path)):d.add(a.path)}if(!c.length&&!d.size)return{note:`No fact with id ${b.join(", ")}. Nothing was deleted.`};let e=["Deleted for good. The listing in your instructions is from when this session opened and still shows it that way until the next one.",1===c.length?`That was the last fact under ${c[0]}, so the note went with it.`:c.length?`That was the last of ${c.join(", ")}, so those notes went with them.`:"",b.length?`No fact with id ${b.join(", ")}, so those were skipped.`:""].filter(Boolean).join(" ");if(!d.size)return{note:e};let{notes:f}=await (0,i.readNotes)([...d],{touch:!1});return{notes:f.map(o),note:e}}})})]),c()}catch(a){c(a)}},!1),617594,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(762008),h=a.i(221214),i=a.i(780946),j=a.i(643020),k=a.i(706210),l=a.i(293480),m=a.i(182248),n=b([h,i]);[h,i]=n.then?(await n)():n;let q={description:`Routines: work that starts by itself, each one a bot, the work and a time — once at a moment, a time of day on chosen days, or every few hours. List them, make one, change one, or delete one. Every start opens a thread like one started by hand; its result reaches the conversation the same way. At most ${f.ROUTINE.max} exist.`,parameters:e.object({action:e.enum(["list","create","change","delete"]),routine:e.string().nullish().describe("With change or delete: the routine, by its name or ID."),bot:e.string().nullish().describe("With create: a name from the bot list. With change: a new bot."),label:e.string().nullish().describe("With create: two or three words naming it, in the user's language. It names every thread the routine opens, on screen and out loud."),request:e.string().nullish().describe("With create: the whole of the work, handed to the bot as written every time it starts. Nobody is there then to fill in what is missing, so everything it needs goes here, in the user's own language and words. Their request, never your reading of it."),at:e.string().nullish().describe('Starts once, at this moment, "YYYY-MM-DD HH:MM" in the user\'s own time, then switches itself off. Count "in an hour" or "tomorrow at eight" from **Now**. Give one of `at`, `time` or `everyHours`.'),time:e.string().nullish().describe('Starts at this time of day, 24-hour "HH:MM" in the user\'s own time, on `days`. Give one of `at`, `time` or `everyHours`.'),days:e.array(e.number().int().min(1).max(7)).nullish().describe("With `time`: the days it starts, 1 Monday to 7 Sunday. Omit for every day."),everyHours:e.number().int().nullish().describe(`Starts again this many hours after it last started, ${f.ROUTINE.minHours} at least. Give one of \`at\`, \`time\` or \`everyHours\`.`),enabled:e.boolean().nullish().describe("With change: false switches it off without deleting it, true back on.")})};function o(a){let b=a.runs[0];return{id:a.id,label:a.label,bot:a.bot,when:(0,j.scheduleText)(a.schedule),enabled:a.enabled,...a.enabled?{next:(0,k.whenOf)((0,k.toDate)(a.nextRunAt))}:{},request:(0,m.clip)(a.request,f.PROMPT_LINE.routineRequest),...b?{lastRun:{thread:b.id,status:b.status,at:(0,k.whenOf)((0,k.toDate)(b.updatedAt)),...b.outcome?{outcome:(0,m.clip)(b.outcome,f.PROMPT_LINE.routineOutcome)}:{}}}:{}}}let r=a=>{if((0,l.isPublicError)(a))return a.message;throw a};async function p(a){let b=(await (0,i.listRoutines)()).map(a=>`"${a.label}"`);return b.length?a?`There is no single routine called "${a}". The routines are: ${b.join(", ")}. Call again with one of those, or its ID.`:`Name the routine. The routines are: ${b.join(", ")}.`:"There are no routines yet."}a.s(["createRoutineTools",0,function(){return{[g.TOOL_NAMES.routine]:(0,d.tool)({description:q.description,inputSchema:q.parameters,execute:async a=>{if("list"===a.action)return{routines:(await (0,i.listRoutines)()).map(o)};let b=function(a){if([a.at,a.time,a.everyHours].filter(Boolean).length>1)return"Give one of `at`, `time` or `everyHours`, not two.";let b=a.at?{kind:"once",at:a.at}:a.time?{kind:"daily",time:a.time,days:a.days?.length?a.days:[1,2,3,4,5,6,7]}:a.everyHours?{kind:"every",hours:a.everyHours}:null;if(!b)return null;let c=j.RoutineScheduleSchema.safeParse(b);return c.success?c.data:c.error.issues[0].message}(a);if("string"==typeof b)return b;if("create"===a.action){if(!b)return"Say when it starts: `at`, `time` (with `days`), or `everyHours`.";let c=j.RoutineInputSchema.safeParse({bot:a.bot??"",label:a.label??"",request:a.request??"",schedule:b});if(!c.success)return`${c.error.issues[0].message}. Nothing was made — call again with bot, label, request and when.`;let d=(await (0,h.listJobBots)()).map(a=>a.name);if(!d.some(a=>a.toLowerCase()===c.data.bot.toLowerCase()))return`There is no bot called "${c.data.bot}". The bots are: ${d.join(", ")}. Nothing was made — call again with one of those.`;let e=await (0,i.createRoutine)(c.data).catch(r);if("string"==typeof e)return e;let f=(0,k.whenOf)((0,k.toDate)(e.nextRunAt));return{...o(e),note:"once"===e.schedule.kind?`${e.bot} starts "${e.label}" once, ${f}, and the routine then switches itself off. The start is a thread of its own, and its result reaches the conversation like any thread's.`:`${e.bot} starts "${e.label}" by itself, ${(0,j.scheduleText)(e.schedule)}, first ${f}. Each start is a thread of its own, and its result reaches the conversation like any thread's.`}}let c=a.routine?await (0,i.resolveRoutine)(a.routine):null;if(!c)return await p(a.routine);if("delete"===a.action)return await (0,i.deleteRoutine)(c.id),`"${c.label}" is deleted and starts no more. The threads it already opened stay.`;let d={...a.bot?{bot:a.bot}:{},...a.label?.trim()?{label:a.label.trim()}:{},...a.request?.trim()?{request:a.request.trim()}:{},...b?{schedule:b}:{},..."boolean"==typeof a.enabled?{enabled:a.enabled}:{}};if(!Object.keys(d).length)return"Nothing to change was given: bot, label, request, when, or enabled.";let e=await (0,i.updateRoutine)(c.id,d).catch(r);return"string"==typeof e?e:e?o(e):await p(a.routine)}})}}]),c()}catch(a){c(a)}},!1),622547,a=>a.a(async(b,c)=>{try{var d=a.i(47919),e=a.i(527990),f=a.i(723885),g=a.i(569572),h=a.i(762008),i=a.i(688034),j=a.i(725466),k=a.i(182248),l=b([j]);[j]=l.then?(await l)():l;let p=`Answer the question from the web. Lead with the answer, then
|
|
89
93
|
what supports it. Say plainly what you could not find or confirm — do not fill
|
|
90
94
|
the gap with a guess. Every number carries the date you saw it. Be brief: this
|
|
91
95
|
is read by another model, not by a person.`,q=f.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.");async function m(a,b,c){let d=await fetch("https://api.exa.ai/search",{method:"POST",signal:c,headers:{"content-type":"application/json","x-api-key":a},body:JSON.stringify({query:b,type:"auto",numResults:g.SEARCH.sources,contents:{text:{maxCharacters:g.SEARCH.excerptChars},livecrawl:"fallback",livecrawlTimeout:5e3}})});if(!d.ok)return{text:`Exa answered ${d.status}: ${(0,k.clip)((await d.text()).trim(),200)}`,sources:[]};let e=(await d.json()).results??[];if(!e.length)return{text:"Nothing came back for that. Try other words, or open the page itself.",sources:[]};let f=e.flatMap(a=>a.url?.trim()?[{url:a.url.trim(),...a.title?.trim()?{title:a.title.trim()}:{}}]:[]);return{text:e.map(a=>{let b=[a.title?.trim(),a.url?.trim()].filter(Boolean).join(" — "),c=a.publishedDate?.slice(0,10);return[c?`${b} \xb7 ${c}`:b,a.text?.trim()].filter(Boolean).join("\n")}).join("\n\n"),sources:f}}async function n(a,b,c){let{text:e,sources:f}=await (0,d.generateText)({model:a.model,tools:a.tools,instructions:p,prompt:b,abortSignal:c}),h=[...new Set(f.flatMap(a=>"url"===a.sourceType?[a.title?`${a.title} — ${a.url}`:a.url]:[]))].slice(0,g.SEARCH.sources);return{text:[e.trim(),h.length?`Sources:
|
|
@@ -99,17 +103,17 @@ ${j.map(a=>{var b;let c,d;return`- ${b=a.startSecond,c=Math.floor(b/60),d=Math.f
|
|
|
99
103
|
${i.trim()}${k}
|
|
100
104
|
`)));return`${o}
|
|
101
105
|
|
|
102
|
-
${await c.fold(m.text,"transcript")}`}})},B=async()=>{let a=await (0,j.resolveMediaRef)("video");if(!a)return null;let b=(0,j.buildVideoModel)(a.ref,a.apiKey);return p({name:k.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:h.default.object({prompt:h.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:h.default.enum(["16:9","9:16"]).nullish().describe("Aspect ratio. Null for 16:9."),seconds:h.default.number().int().min(2).max(10).nullish().describe("Length in seconds, 2 to 10. Null for the provider's default.")}),execute:async({prompt:a,aspectRatio:c,seconds:d},{sandbox:e,artifacts:g,abortSignal:h})=>{let{video:i}=await (0,f.experimental_generateVideo)({model:b,prompt:a,aspectRatio:c??"16:9",duration:d??void 0,abortSignal:h}),j=await r(e,g,q(a,w(i.mediaType,"mp4")),i.uint8Array);return v(j)}})};async function t(){return(await Promise.all([u(y),u(z),u(A),u(B)])).filter(a=>null!==a)}async function u(a){try{return await a()}catch(a){return m.logger.warn(`studio: a tool could not be built — ${(0,n.errorToString)(a)}`),null}}a.s(["loadStudio",0,t]),c()}catch(a){c(a)}},!1),644468,a=>a.a(async(b,c)=>{try{var d=a.i(723885),e=a.i(569572),f=a.i(317844),g=a.i(947950),h=a.i(182248),i=a.i(500777),j=b([f,g,i]);async function k(a){let[b,c]=await Promise.all([!a||a===e.STUDIO_SERVER?(0,i.loadStudio)():[],a===e.STUDIO_SERVER?[]:(0,g.listToolNames)(a)]);return[...b.map(a=>({server:e.STUDIO_SERVER,name:a.name})),...c]}[f,g,i]=j.then?(await j)():j;let p=async()=>{let[a,b]=await Promise.all([(0,i.loadStudio)(),(0,g.listServerNames)()]);return[...a.length?[e.STUDIO_SERVER]:[],...b.map(a=>a.name)]};async function l(a,b){if(a===e.STUDIO_SERVER){let a=new Set(b);return(await (0,i.loadStudio)()).filter(b=>a.has(b.name)).map(a=>({name:a.name,description:a.description,inputSchema:d.default.toJSONSchema(a.inputSchema)}))}return(await (0,g.findToolSchemas)(a,b)).map(a=>({name:a.name,description:a.description??null,inputSchema:a.inputSchema??null}))}async function m(a,b,c,d,{artifacts:g,abortSignal:i}){let j=AbortSignal.timeout(e.CONNECTED_TOOL_TIMEOUT_MS),k=i?AbortSignal.any([i,j]):j;try{let f=b===e.STUDIO_SERVER?await n(a,c,d,g,k):await o(b,c,d,k);if("string"!=typeof f)return f;return{status:"ok",text:await a.fold(f,`${b}-${c}`)}}catch(a){if(a instanceof f.McpAuthRequiredError)return{status:"auth_required",server:b,authorizationUrl:a.authorizationUrl};if(j.aborted&&!i?.aborted)return{status:"error",text:`${c} on ${b} gave no answer in ${e.CONNECTED_TOOL_TIMEOUT_MS/6e4} minutes and was given up on.`};return{status:"error",text:(0,h.errorToString)(a)}}}async function n(a,b,c,d,f){let g=(await (0,i.loadStudio)()).find(a=>a.name===b);if(!g)throw Error(`"${b}" is not in the ${e.STUDIO_SERVER} right now — the key that runs it is gone.`);return g.execute(c??{},{sandbox:a,artifacts:d,abortSignal:f})}async function o(a,b,c,d){let e=function(a){let b=a??{},c=!0===b.isError;if(!Array.isArray(b.content)){let a=void 0===b.toolResult?"":"string"==typeof b.toolResult?b.toolResult:JSON.stringify(b.toolResult);return{status:c?"error":"ok",text:a||q(c)}}let d=b.content.map(a=>"text"===a.type&&"string"==typeof a.text?a.text:`[${a.type}${a.mimeType?` ${a.mimeType}`:""} — not shown]`).join("\n").trim();return{status:c?"error":"ok",text:d||q(c)}}(await f.mcpManager.callTool(a,b,c,d));return"ok"===e.status?e.text:e}let q=a=>a?"The tool failed without a message.":"Done.";a.s(["callConnectedTool",0,m,"findConnectedSchemas",0,l,"listConnectedServerNames",0,p,"listConnectedToolNames",0,k]),c()}catch(a){c(a)}},!1),547613,a=>{"use strict";var b=a.i(750227),c=a.i(527990),d=a.i(723885),e=a.i(569572),f=a.i(762008),g=a.i(641301),h=a.i(821415);let
|
|
106
|
+
${await c.fold(m.text,"transcript")}`}})},B=async()=>{let a=await (0,j.resolveMediaRef)("video");if(!a)return null;let b=(0,j.buildVideoModel)(a.ref,a.apiKey);return p({name:k.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:h.default.object({prompt:h.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:h.default.enum(["16:9","9:16"]).nullish().describe("Aspect ratio. Null for 16:9."),seconds:h.default.number().int().min(2).max(10).nullish().describe("Length in seconds, 2 to 10. Null for the provider's default.")}),execute:async({prompt:a,aspectRatio:c,seconds:d},{sandbox:e,artifacts:g,abortSignal:h})=>{let{video:i}=await (0,f.experimental_generateVideo)({model:b,prompt:a,aspectRatio:c??"16:9",duration:d??void 0,maxRetries:0,abortSignal:h}),j=await r(e,g,q(a,w(i.mediaType,"mp4")),i.uint8Array);return v(j)}})};async function t(){return(await Promise.all([u(y),u(z),u(A),u(B)])).filter(a=>null!==a)}async function u(a){try{return await a()}catch(a){return m.logger.warn(`studio: a tool could not be built — ${(0,n.errorToString)(a)}`),null}}a.s(["loadStudio",0,t]),c()}catch(a){c(a)}},!1),644468,a=>a.a(async(b,c)=>{try{var d=a.i(723885),e=a.i(569572),f=a.i(317844),g=a.i(947950),h=a.i(182248),i=a.i(500777),j=b([f,g,i]);async function k(a){let[b,c]=await Promise.all([!a||a===e.STUDIO_SERVER?(0,i.loadStudio)():[],a===e.STUDIO_SERVER?[]:(0,g.listToolNames)(a)]);return[...b.map(a=>({server:e.STUDIO_SERVER,name:a.name})),...c]}[f,g,i]=j.then?(await j)():j;let p=async()=>{let[a,b]=await Promise.all([(0,i.loadStudio)(),(0,g.listServerNames)()]);return[...a.length?[e.STUDIO_SERVER]:[],...b.map(a=>a.name)]};async function l(a,b){if(a===e.STUDIO_SERVER){let a=new Set(b);return(await (0,i.loadStudio)()).filter(b=>a.has(b.name)).map(a=>({name:a.name,description:a.description,inputSchema:d.default.toJSONSchema(a.inputSchema)}))}return(await (0,g.findToolSchemas)(a,b)).map(a=>({name:a.name,description:a.description??null,inputSchema:a.inputSchema??null}))}async function m(a,b,c,d,{artifacts:g,abortSignal:i}){let j=AbortSignal.timeout(e.CONNECTED_TOOL_TIMEOUT_MS),k=i?AbortSignal.any([i,j]):j;try{let f=b===e.STUDIO_SERVER?await n(a,c,d,g,k):await o(b,c,d,k);if("string"!=typeof f)return f;return{status:"ok",text:await a.fold(f,`${b}-${c}`)}}catch(a){if(a instanceof f.McpAuthRequiredError)return{status:"auth_required",server:b,authorizationUrl:a.authorizationUrl};if(j.aborted&&!i?.aborted)return{status:"error",text:`${c} on ${b} gave no answer in ${e.CONNECTED_TOOL_TIMEOUT_MS/6e4} minutes and was given up on.`};return{status:"error",text:(0,h.errorToString)(a)}}}async function n(a,b,c,d,f){let g=(await (0,i.loadStudio)()).find(a=>a.name===b);if(!g)throw Error(`"${b}" is not in the ${e.STUDIO_SERVER} right now — the key that runs it is gone.`);return g.execute(c??{},{sandbox:a,artifacts:d,abortSignal:f})}async function o(a,b,c,d){let e=function(a){let b=a??{},c=!0===b.isError;if(!Array.isArray(b.content)){let a=void 0===b.toolResult?"":"string"==typeof b.toolResult?b.toolResult:JSON.stringify(b.toolResult);return{status:c?"error":"ok",text:a||q(c)}}let d=b.content.map(a=>"text"===a.type&&"string"==typeof a.text?a.text:`[${a.type}${a.mimeType?` ${a.mimeType}`:""} — not shown]`).join("\n").trim();return{status:c?"error":"ok",text:d||q(c)}}(await f.mcpManager.callTool(a,b,c,d));return"ok"===e.status?e.text:e}let q=a=>a?"The tool failed without a message.":"Done.";a.s(["callConnectedTool",0,m,"findConnectedSchemas",0,l,"listConnectedServerNames",0,p,"listConnectedToolNames",0,k]),c()}catch(a){c(a)}},!1),547613,a=>{"use strict";var b=a.i(750227),c=a.i(527990),d=a.i(723885),e=a.i(569572),f=a.i(762008),g=a.i(641301),h=a.i(821415),i=a.i(389359);let j=`## The shell here
|
|
103
107
|
|
|
104
108
|
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.
|
|
105
109
|
|
|
106
110
|
Nothing is watching it. A command that stops to ask never gets an answer and is killed after ${e.EXEC_TIMEOUT_MS/1e3}s, so pass the flag that skips the question (\`-y\`, \`--yes\`, \`--no-input\`), and send anything genuinely long to the background with its output redirected to a file.
|
|
107
111
|
|
|
108
|
-
Keys are not in the environment: every variable named like a key, a token or a secret is removed before the shell starts. An empty one is not an unset one — say which it was, and ask for what a command needs.`;a.s(["createWorkspaceTools",0,(a,e)=>{let
|
|
109
|
-
${c(f)}`}:d.push({role:"assistant",content:c(f)})}return d}])},641301,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(569572),e=a.i(821415);let f=a=>`${(0,e.botFolder)(a)}/memory`;async function g(a,b=d.BOT_MEMORY_LIMITS.files){let i=f(a),j=(0,c.join)(e.WORKSPACE,i),k=(await h(j)).sort((a,b)=>b.info.mtimeMs-a.info.mtimeMs),m=await Promise.all(k.slice(0,b).map(async({name:a,info:b})=>({file:a,path:`${i}/${a}`,line:await l((0,c.join)(j,a)),at:new Date(b.mtimeMs),bytes:b.size})));return{folder:i,entries:m,total:k.length}}async function h(a){let d=await (0,b.readdir)(a).catch(()=>[]);return(await Promise.all(d.filter(a=>!a.startsWith(".")).map(async d=>{let e=await (0,b.stat)((0,c.join)(a,d)).catch(()=>null);return e?.isFile()?{name:d,info:e}:null}))).filter(a=>null!==a)}async function i(a){let g=(0,c.join)(e.WORKSPACE,f(a)),i=new Map;return await Promise.all((await h(g)).map(async({name:a,info:e})=>{let f=e.size>4*d.BOT_MEMORY_LIMITS.chars?null:await (0,b.readFile)((0,c.join)(g,a),"utf8").catch(()=>null);i.set(a,{text:null!==f&&k(f)<=d.BOT_MEMORY_LIMITS.chars?f:null,size:e.size,mtimeMs:e.mtimeMs,atime:e.atime,mtime:e.mtime})})),i}async function j(a,g){let i=f(a),j=(0,c.join)(e.WORKSPACE,i),{files:l,chars:m}=d.BOT_MEMORY_LIMITS,n=[],o=[],p=0;for(let{name:a,info:d}of(await h(j))){p+=1;let e=g.get(a);if(e&&e.size===d.size&&e.mtimeMs===d.mtimeMs)continue;let f=(0,c.join)(j,a),h=k(await (0,b.readFile)(f,"utf8").catch(()=>""));if(h<=m){e||o.push(a);continue}let l=`${h.toLocaleString("en-US")} characters, past the ${m.toLocaleString("en-US")} a memory file holds`;e?null!==e.text?(await (0,b.writeFile)(f,e.text),await (0,b.utimes)(f,e.atime,e.mtime),n.push(`Not kept: \`${i}/${a}\` came to ${l}, so it is back as it was. Write it again shorter.`)):n.push(`\`${i}/${a}\` is ${l}. Shorten it.`):(await (0,b.rm)(f,{force:!0}),p-=1,n.push(`Not kept: \`${i}/${a}\` came to ${l}, so it was removed. Write it again shorter.`))}if(p>l&&o.length){await Promise.all(o.map(a=>(0,b.rm)((0,c.join)(j,a),{force:!0})));let a=o.map(a=>`\`${i}/${a}\``).join(", ");n.push(`Not kept: your memory holds ${l} files at most and this made ${p}, so ${a} ${1===o.length?"was":"were"} removed. Delete or merge files no longer worth keeping, then write it again.`)}return n.length?n.join("\n"):null}let k=a=>[...a.trim()].length;async function l(a){let c=await (0,b.open)(a,"r").catch(()=>null);if(!c)return"";try{let a=Buffer.alloc(1024),{bytesRead:b}=await c.read(a,0,1024,0),d=a.toString("utf8",0,b).split("\n").map(a=>a.trim()).filter(Boolean);if("---"===d[0]){let a=d.find(a=>a.startsWith("description:"));if(a)return a.slice(12).trim().replace(/^["']|["']$/g,"");let b=d.indexOf("---",1);return b>0?(d[b+1]??"").replace(/^#+\s*/,""):""}return(d[0]??"").replace(/^#+\s*/,"")}finally{await c.close()}}a.s(["botMemoryFolder",0,f,"holdBotMemory",0,i,"keepBotMemory",0,j,"listBotMemory",0,g])},654034,a=>a.a(async(b,c)=>{try{var d=a.i(47919),e=a.i(527990),f=a.i(569572),g=a.i(738131),h=a.i(875931),i=a.i(735502),j=a.i(978876),k=a.i(762008),l=a.i(346580),m=a.i(446957),n=a.i(487591),o=a.i(821415),p=a.i(176668),q=a.i(987674),r=a.i(221214),s=a.i(
|
|
112
|
+
Keys are not in the environment: every variable named like a key, a token or a secret is removed before the shell starts. An empty one is not an unset one — say which it was, and ask for what a command needs.`;a.s(["createWorkspaceTools",0,(a,e)=>{let k=!0===e.guide,l=async a=>{let b=e.bot;if(!b)return{result:await a(),memory:null};let c=await (0,g.holdBotMemory)(b);return{result:await a(),memory:await (0,g.keepBotMemory)(b,c)}},m=(0,c.tool)({description:i.BASH?"Run a bash command.":"Run a command in sh: this machine has no bash, so bash-only syntax fails.",inputSchema:d.default.object({command:d.default.string(),description:d.default.string().nullish().describe("One short line for the user: what this command does and why. Shown on their screen while it runs — not a restatement of the command.")}),execute:async({command:b},{abortSignal:c})=>{let{result:d,memory:f}=await l(()=>a.exec(b,{signal:c,env:e.env,timeoutMs:e.timeoutMs})),g=f?{...d,memory:f}:d;return k?(k=!1,{...g,guide:j}):g}});if(!e.write)return{[f.TOOL_NAMES.bash]:m};let n=(0,c.tool)({description:"Write a whole file — what was there is gone. Parent directories are created.",inputSchema:d.default.object({path:d.default.string().describe("Relative to the working directory — under one of its folders — or absolute"),content:d.default.string(),description:d.default.string().nullish().describe("One short line for the user: what this file is. Shown on their screen next to the path.")}),execute:async({path:c,content:d})=>{let f,g=a.resolve(c),i=(0,h.writeRefusal)(g,e.bot);if(i)return i;let{memory:j}=await l(()=>a.writeFile(c,d));return j??`Wrote ${(f=(0,b.relative)(a.cwd,g))&&!f.startsWith("..")?f:g} (${d.split("\n").length} lines)`}});return{[f.TOOL_NAMES.bash]:m,[f.TOOL_NAMES.write_file]:n}}])},346580,a=>{"use strict";a.s(["asWords",0,function(a,b,c=a=>a){let d=[];for(let e of a){if("tool"===e.role)continue;if("system"===e.role){d.push(e);continue}if("user"===e.role){d.push("string"==typeof e.content?{role:"user",content:c(e.content)}:e);continue}let a="string"==typeof e.content?[{type:"text",text:e.content}]:e.content,f=a.flatMap(a=>"text"===a.type?[a.text]:[]).join("\n").trim()||a.flatMap(a=>"tool-call"===a.type?[b(a.toolName,a.input)]:[]).join("\n");if(!f)continue;let g=d.at(-1);g?.role==="assistant"&&"string"==typeof g.content?d[d.length-1]={role:"assistant",content:`${g.content}
|
|
113
|
+
${c(f)}`}:d.push({role:"assistant",content:c(f)})}return d}])},641301,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(569572),e=a.i(821415);let f=a=>`${(0,e.botFolder)(a)}/memory`;async function g(a,b=d.BOT_MEMORY_LIMITS.files){let i=f(a),j=(0,c.join)(e.WORKSPACE,i),k=(await h(j)).sort((a,b)=>b.info.mtimeMs-a.info.mtimeMs),m=await Promise.all(k.slice(0,b).map(async({name:a,info:b})=>({file:a,path:`${i}/${a}`,line:await l((0,c.join)(j,a)),at:new Date(b.mtimeMs),bytes:b.size})));return{folder:i,entries:m,total:k.length}}async function h(a){let d=await (0,b.readdir)(a).catch(()=>[]);return(await Promise.all(d.filter(a=>!a.startsWith(".")).map(async d=>{let e=await (0,b.stat)((0,c.join)(a,d)).catch(()=>null);return e?.isFile()?{name:d,info:e}:null}))).filter(a=>null!==a)}async function i(a){let g=(0,c.join)(e.WORKSPACE,f(a)),i=new Map;return await Promise.all((await h(g)).map(async({name:a,info:e})=>{let f=e.size>4*d.BOT_MEMORY_LIMITS.chars?null:await (0,b.readFile)((0,c.join)(g,a),"utf8").catch(()=>null);i.set(a,{text:null!==f&&k(f)<=d.BOT_MEMORY_LIMITS.chars?f:null,size:e.size,mtimeMs:e.mtimeMs,atime:e.atime,mtime:e.mtime})})),i}async function j(a,g){let i=f(a),j=(0,c.join)(e.WORKSPACE,i),{files:l,chars:m}=d.BOT_MEMORY_LIMITS,n=[],o=[],p=0;for(let{name:a,info:d}of(await h(j))){p+=1;let e=g.get(a);if(e&&e.size===d.size&&e.mtimeMs===d.mtimeMs)continue;let f=(0,c.join)(j,a),h=k(await (0,b.readFile)(f,"utf8").catch(()=>""));if(h<=m){e||o.push(a);continue}let l=`${h.toLocaleString("en-US")} characters, past the ${m.toLocaleString("en-US")} a memory file holds`;e?null!==e.text?(await (0,b.writeFile)(f,e.text),await (0,b.utimes)(f,e.atime,e.mtime),n.push(`Not kept: \`${i}/${a}\` came to ${l}, so it is back as it was. Write it again shorter.`)):n.push(`\`${i}/${a}\` is ${l}. Shorten it.`):(await (0,b.rm)(f,{force:!0}),p-=1,n.push(`Not kept: \`${i}/${a}\` came to ${l}, so it was removed. Write it again shorter.`))}if(p>l&&o.length){await Promise.all(o.map(a=>(0,b.rm)((0,c.join)(j,a),{force:!0})));let a=o.map(a=>`\`${i}/${a}\``).join(", ");n.push(`Not kept: your memory holds ${l} files at most and this made ${p}, so ${a} ${1===o.length?"was":"were"} removed. Delete or merge files no longer worth keeping, then write it again.`)}return n.length?n.join("\n"):null}let k=a=>[...a.trim()].length;async function l(a){let c=await (0,b.open)(a,"r").catch(()=>null);if(!c)return"";try{let a=Buffer.alloc(1024),{bytesRead:b}=await c.read(a,0,1024,0),d=a.toString("utf8",0,b).split("\n").map(a=>a.trim()).filter(Boolean);if("---"===d[0]){let a=d.find(a=>a.startsWith("description:"));if(a)return a.slice(12).trim().replace(/^["']|["']$/g,"");let b=d.indexOf("---",1);return b>0?(d[b+1]??"").replace(/^#+\s*/,""):""}return(d[0]??"").replace(/^#+\s*/,"")}finally{await c.close()}}a.s(["botMemoryFolder",0,f,"holdBotMemory",0,i,"keepBotMemory",0,j,"listBotMemory",0,g])},654034,a=>a.a(async(b,c)=>{try{var d=a.i(47919),e=a.i(527990),f=a.i(569572),g=a.i(738131),h=a.i(875931),i=a.i(735502),j=a.i(978876),k=a.i(762008),l=a.i(346580),m=a.i(446957),n=a.i(487591),o=a.i(821415),p=a.i(176668),q=a.i(987674),r=a.i(221214),s=a.i(109955),t=a.i(344853),u=b([g,h,i,j,r,t]);[g,h,i,j,r,t]=u.then?(await u)():u;let z=f.BOT_RUN.steps;async function v(a,b){var c,l;let u,v,y,B,C,D,E,F,G,H=b.parent??null,I=await (0,r.findJobBot)(a.bot.trim()),J=I?.name??a.bot.trim(),K=a=>b.emit({...a,bot:J,parent:H});if(!I)return void await K({type:"error",message:`No bot named "${a.bot}". Use a name from the list.`,retry:!1});let L=a.messages,M=await ((c=I).provider&&c.model?(0,h.getTextModel)({provider:c.provider,model:c.model}):(0,h.resolveDefaultModel)().then(h.getTextModel)),N=b.threadId?await (0,t.findThread)(b.threadId):null,[O,{own:P,artifacts:Q}]=await Promise.all([b.threadId?(0,o.openJobScratch)(b.threadId,N?.label??"job"):null,(0,o.openBotFolders)(J)]),R=b.session??(b.threadId?(0,o.botBrowserSession)(b.threadId,J):null),[S,T]=await Promise.all([(0,i.loadBotPrompt)(J,I.systemPrompt,{thread:b.threadId??null,owner:b.owner,caller:b.caller},{scratch:O,own:P,artifacts:Q}),(0,g.loadTools)({target:"bot",bot:J,thread:b.threadId??null,session:R,model:M})]),U=Math.min(await (0,h.compactBudget)(M.ref,I.compactAt),b.contextBudget||1/0),V=await (0,h.runEffort)(M.ref,I.effort),W=!1,X={...T,[k.TOOL_NAMES.send_message]:(0,e.tool)({description:j.sendMessageSpec.description,inputSchema:j.sendMessageSpec.parameters,execute:async(a,c)=>{let d=await b.send({...a,id:c.toolCallId});if("question"===a.kind&&(W=!0),!d||"object"!=typeof d||!("to"in d))return d;let e=String(d.to);return e===s.ROOM_THURSDAY?d:{...d,note:`${e} has it now. When they finish, their answer — what they did and where the files are — comes to you as a new message and wakes you. Until then you do not know it: do not report it, guess it or do it yourself, and do not watch their folder. Go on with other work, or end your turn if there is none; the thread stays open.`}}})},Y=new Set,Z=(l=f.BOT_RUN.silenceMs,v=new AbortController,y=0,B=!1,C=()=>{clearTimeout(u),u=void 0,B||y>0||(u=setTimeout(()=>{v.abort(new DOMException(`The model sent nothing for ${Math.round(l/6e4)} minutes.`,"TimeoutError"))},l))},{signal:v.signal,touch:C,hold:()=>{y+=1,C()},release:()=>{y=Math.max(0,y-1),C()},end:()=>{B=!0,C()}});for(let[a,c]of Object.entries(X)){let d=c.execute;d&&(c.execute=(c,e)=>{let f=(async()=>{b.signal?.throwIfAborted(),await K({type:"tool",id:e.toolCallId,name:a,input:c}),Z.hold();try{b.signal?.throwIfAborted();let f=await d(c,e);if(f&&"object"==typeof f&&Symbol.asyncIterator in f){let a;for await(let b of f)a=b;f=a}return await K({type:"tool-result",id:e.toolCallId,name:a,output:f}),f}catch(b){throw await K({type:"tool-result",id:e.toolCallId,name:a,output:(0,h.modelErrorToString)(b),error:!0}),b}finally{Z.release()}})();return Y.add(f),f.finally(()=>Y.delete(f)).catch(()=>{}),f})}let $=Promise.resolve(),_=()=>{},aa=0,ab=new d.ToolLoopAgent({model:M.model,instructions:S.text,tools:X,reasoning:V,stopWhen:[(0,d.stepCountIs)(z),()=>W],prepareStep:async({stepNumber:a,steps:c,messages:d})=>{await $,b.signal?.throwIfAborted();let e={},f=(c.at(-1)?.usage.inputTokens??0)||d.reduce((a,b)=>a+(0,q.estimateTokens)("string"==typeof b.content?b.content:JSON.stringify(b.content))+4,0);aa=f;let g=d,h=b.compactNow?.()??!1;if((f>U||h)&&d.length>2){Z.hold();let a=await x(M.model,X,d,{signal:b.signal,budget:U,instructions:S.text}).finally(Z.release);p.logger.debug(`compacted ${d.length} messages at ${f} tokens (budget ${U})`);let c=`${a.text}${await w(N?.id??null,d,O)}`;await K({type:"compact",text:c,usage:a.usage,messages:d.length,tokens:f}),g=[d[0],{role:"user",content:c}]}let i=a>0?await b.notes?.()??[]:[];return(i.length&&(g=[...g,...i.map(a=>({role:"user",content:a}))]),g===d)?e:{...e,messages:g}}}),ac=(D=[],E=[],F=!1,{push(a){let b=E.shift();b?b(a):D.push(a)},take(){let a=D.shift();return a?Promise.resolve(a):F?Promise.resolve(null):new Promise(a=>E.push(a))},end(){for(let a of(F=!0,E.splice(0)))a(null)}}),ad=b.signal?AbortSignal.any([b.signal,Z.signal]):Z.signal;Z.touch();let ae=new AbortController,af=AbortSignal.any([ad,ae.signal]);try{G=await ab.stream({messages:L,abortSignal:af,onStepEnd:a=>{$=new Promise(a=>{_=a}),ac.push({messages:function(a){if(!a.toolResults.length)return a.response.messages;let b=new Map(a.toolResults.map(a=>[a.toolCallId,a.output]));return a.response.messages.map(a=>"tool"!==a.role?a:{...a,content:a.content.map(a=>{if("tool-result"!==a.type||!b.has(a.toolCallId))return a;let c=b.get(a.toolCallId);return{...a,output:"string"==typeof c?{type:"text",value:c}:{type:"json",value:c}}})})}(a),usage:A(a.usage)})}})}catch(a){throw Z.end(),ae.abort(),await Promise.allSettled([...Y]),a}let ag="",ah="",ai=null,aj=a=>{p.logger.error(`${J}: the model run broke`,a);let b=(0,h.modelErrorToString)(a),c=!(0,h.isProviderRefusal)(a);if(!(0,h.isContextOverflow)(a))return{type:"error",message:b,retry:c};let d=Math.floor(Math.min(U,aa||U)*f.BOT_RUN.overflowShrink);return{type:"error",message:b,budget:Math.max(m.COMPACT_AT_MIN,d),retry:c}};ad.addEventListener("abort",()=>{ac.end(),_()},{once:!0});try{for await(let a of G.stream)switch(Z.touch(),a.type){case"start-step":ah="",ag="";break;case"text-delta":ag+=a.text;break;case"text-end":{let a=ag.trim();if(ag="",!a)break;ah=[ah,a].filter(Boolean).join("\n\n"),await K({type:"text",text:a});break}case"tool-call":await K({type:"tool",id:a.toolCallId,name:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:a.providerMetadata});break;case"tool-result":await K({type:"tool-result",id:a.toolCallId,name:a.toolName,output:a.output});break;case"tool-error":await K({type:"tool-result",id:a.toolCallId,name:a.toolName,output:(0,h.modelErrorToString)(a.error),error:!0});break;case"finish-step":{ai=a.finishReason;let b=await ac.take();b&&await K({type:"step",...b,budget:U}),_();break}case"abort":if(b.signal?.aborted)return;await K(aj(a.reason??"The model stopped sending."));return;case"error":await K(aj(a.error));return}}finally{ae.abort(),ac.end(),Z.end(),_(),await Promise.allSettled([...Y]),R&&(0,n.renewSignIns)(R).catch(a=>p.logger.warn(`${J}: kept sign-ins were not renewed`,a))}try{await G.finalStep}catch(a){if(b.signal?.aborted)return;await K(aj(a));return}"content-filter"===ai?await K({type:"error",message:"The provider's content filter stopped the response.",retry:!1}):await K({type:"turn-end",text:ah,stopped:!W&&("length"===ai||"error"===ai||"tool-calls"===ai)})}async function w(a,b,c){try{let d=a?await (0,t.listWrittenPaths)(a):(0,t.writtenPathsIn)(b.map(a=>a.content)),e=await (0,o.filesOnDisk)(d,c);if(!e.length)return"";let g=e.slice(-f.BOT_RUN.compactFiles),h=e.length-g.length,i=g.map(a=>`- ${a}`);return h&&i.unshift(`- …and ${h} older ones`),`
|
|
110
114
|
|
|
111
115
|
Files this job has on disk now — open one rather than fetching again what is in it:
|
|
112
|
-
${i.join("\n")}`}catch(a){return p.logger.warn("files under the summary could not be listed",a),""}}async function
|
|
116
|
+
${i.join("\n")}`}catch(a){return p.logger.warn("files under the summary could not be listed",a),""}}async function x(a,b,c,d){let e;try{return await y(a,b,c,d)}catch(a){if(d.signal?.aborted)throw a;e=a}if((0,h.isContextOverflow)(e)){let f=(0,l.asWords)(c,(a,b)=>`${a}: ${(0,t.argumentLine)(a,b)}`);try{return await y(a,b,f,d)}catch(a){if(d.signal?.aborted)throw a;e=a}}throw Error(`Could not compact the context (${(0,h.modelErrorToString)(e)}).`,{cause:e})}async function y(a,b,c,e){let g,{text:h,usage:i}=await (0,d.generateText)({model:a,instructions:e.instructions,tools:b,toolChoice:"none",messages:[...c,{role:"user",content:(g=(a=>{let{min:b,max:c,perTokens:d}=f.BOT_RUN.summaryWords;return Math.min(c,Math.max(b,Math.round(a/d)))})(e.budget),`Compact your context. The first message above — who handed you the job, and the job — stays exactly as it is. Everything after it is replaced by what you write now, and you carry on from that first message and this alone; nothing else above can be read again. Write it for a fresh copy of you that has your tools, your instructions and that first message, but has seen none of the rest.
|
|
113
117
|
|
|
114
118
|
Cover all of it, and prefer a fact over a description of a fact:
|
|
115
119
|
|
|
@@ -122,9 +126,9 @@ Cover all of it, and prefer a fact over a description of a fact:
|
|
|
122
126
|
|
|
123
127
|
Plain text, under ${g} words. No preamble, no headings about the summary itself, no account of how you have been going.`)}],abortSignal:e.signal,timeout:f.BOT_RUN.silenceMs}),j=h.trim();if(!j)throw Error("The summary of the context came back empty, so there is nothing to carry on from.");return{text:`Everything between the first message and here was compacted. Below is your own summary of it; carry on from the first message and this.
|
|
124
128
|
|
|
125
|
-
${j}`,usage:
|
|
129
|
+
${j}`,usage:A(i)}}let A=a=>({input:a.inputTokens??0,output:a.outputTokens??0});a.s(["resumeTranscript",0,function(a,b=new Map){let c=new Map,d=new Set;for(let b of a)if(("tool"===b.role||"assistant"===b.role)&&Array.isArray(b.content))for(let a of b.content)"tool-result"===a.type&&(c.has(a.toolCallId)||c.set(a.toolCallId,a),"assistant"===b.role&&d.add(a.toolCallId));let e=[],f=new Set;for(let g of a){if("tool"===g.role){let a=g.content.filter(a=>"tool-result"!==a.type);a.length&&e.push({...g,content:a});continue}if("assistant"!==g.role||"string"==typeof g.content){e.push(g);continue}let a=[],h=[];for(let e of g.content){if("tool-call"!==e.type){h.push(e);continue}if(f.has(e.toolCallId))continue;let g=e.input;if("string"==typeof g)try{g=JSON.parse(g)}catch{g=void 0}if(!e.toolCallId||void 0===g){h.push({type:"text",text:"A tool argument stream was interrupted before a complete call was recorded. Inspect the saved work before continuing."});continue}let i=e.toolName===k.TOOL_NAMES.send_message?b.get(e.toolCallId):void 0,j=c.get(e.toolCallId)??(i?{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"json",value:i}}:void 0);if(e.providerExecuted&&(!j||!d.has(e.toolCallId))){h.push({type:"text",text:j?`The provider operation ${e.toolName} returned this data before its native continuation was interrupted: ${JSON.stringify(j.output)}`:`The provider operation ${e.toolName} was interrupted without a recorded result. Its remote execution state is unknown.`});continue}f.add(e.toolCallId),h.push({...e,input:g}),d.has(e.toolCallId)||a.push(j??{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:"No result: execution was interrupted before a result was recorded. The outcome is unknown. Inspect the current state before repeating the action."}})}h.length&&e.push({...g,content:h}),a.length&&e.push({role:"tool",content:a})}return e},"runBot",0,v]),c()}catch(a){c(a)}},!1),674986,a=>a.a(async(b,c)=>{try{var d=a.i(136340),e=a.i(203469),f=a.i(569572),g=a.i(875931),h=a.i(735502),i=a.i(569549),j=a.i(684321),k=a.i(821415),l=a.i(956802),m=a.i(176668),n=a.i(293480),o=a.i(8412),p=a.i(182248),q=a.i(221214),r=a.i(654034),s=a.i(446957),t=a.i(839430),u=a.i(109955),v=a.i(344853),w=b([g,h,i,q,r,t,v]);[g,h,i,q,r,t,v]=w.then?(await w)():w;let K=globalThis.__roomRuns??=new Map,L=globalThis.__roomThreadLock??=(0,o.createKeyedLock)(),M=globalThis.__roomCompactAsked??=new Set,N=(a,b)=>`${a}
|
|
126
130
|
${b}`;async function x(a){let b=await (0,q.findJobBot)(a.bot);(!b||b.disabled)&&(0,n.publicError)("Choose an enabled bot.");let{from:c,routine:d,...e}={...a,bot:b.name},f=(0,h.buildThreadOpening)({bot:e.bot,request:e.request,from:c,routine:d}),g=await (0,v.insertThread)({...e,routineId:d?.id??null,opening:f});return await z(g.id),g.id}async function y(a,b,c="user",d,e){let f=null;return await L(a,async()=>{let g=await (0,v.findThread)(a);if(g||(0,n.publicError)("No such thread."),d){let b=(await (0,t.listRoomWork)(a)).find(a=>a.bot.toLowerCase()===d.trim().toLowerCase());b&&b.bot!==u.ROOM_THURSDAY||(0,n.publicError)("Choose a participant in this thread."),d=b.bot}b.trim()===s.THREAD_CONTINUE&&(0,s.isAppStop)(g.pending)?(await (0,t.resumeRoom)(a),(await (0,t.listRoomWork)(a)).some(a=>"queued"===a.state)||(f=await (0,t.tellRoom)(a,"Continue from the saved conversation.","user"===c?u.ROOM_USER:u.ROOM_THURSDAY,d,void 0,!1))):f=await (0,t.tellRoom)(a,b,"user"===c?u.ROOM_USER:u.ROOM_THURSDAY,d,e)}),await z(a),f}async function z(a){await L(a,async()=>{for(let b=0;b<2;b++){let b;for(;b=await (0,t.claimRoomWork)(a);)!function(a){let b,c=new AbortController,d=new Promise(a=>{b=a});K.set(a.id,{threadId:a.threadId,stop:c,done:d}),A(a,c.signal).catch(b=>m.logger.error(`thread ${a.threadId}: participant`,b)).finally(()=>{K.delete(a.id),b(),z(a.threadId).catch(b=>m.logger.error(`thread ${a.threadId}: scheduling`,b))})}(b);await (0,t.settleRoom)(a)}})}async function A(a,b){let c=await B(a,b);if(c?.failure?.retry&&!b.aborted&&(await (0,t.noteRoomBreak)(a,c.failure.message),await (0,d.setTimeout)(f.BOT_RUN.retryMs,void 0,{signal:b}).catch(()=>{}),b.aborted||(c=await B(a,b))),!c||b.aborted)return;let g=c.failure?.message,h=c.ending;if(g||!h||h.stopped){let b=g??"The turn was interrupted. Continue from the saved conversation.";L(a.threadId,async()=>{let c=(await (0,t.listRoomWork)(a.threadId)).find(b=>b.id===a.id);if(c?.state!=="running"||c.generation!==a.generation)return;let d=C(a.threadId);await (0,t.pauseRoom)(a.threadId,b),await d}).catch(b=>m.logger.error(`thread ${a.threadId}: pausing`,b));return}await (0,t.finishRoomWork)(a,h.text);let n=await (0,v.findThread)(a.threadId);if(n?.status==="done"){let a=(0,p.plainText)(n.outcome??"").slice(0,f.FINISHED_NOTICE.words);e.presence.watching||await (0,i.isAnyCallLive)()||(0,l.desktopNotify)(n.label,a);let b=await (0,k.filesOnDisk)((0,j.pathsIn)(n.outcome??""),null);e.appEvents.emit({type:"finished",threadId:n.id,label:n.label,bot:n.bot,words:a,paths:(0,j.leadFirst)(b)})}}async function B(a,b){let c=new O(a,b),d=null,e=null;try{let f=await (0,v.findThread)(a.threadId);if(!f)return null;(await (0,t.listParticipantTranscript)(a.threadId,a.bot)).length||await (0,t.appendRoomMessage)(a.threadId,{bot:a.bot,parent:a.id,role:"user",content:`Request: ${f.request}
|
|
127
|
-
Coordinator: ${f.bot}. Continue as ${a.bot} in this thread.`,hidden:!0}),await (0,t.consumeRoomInbox)(a);let g=await (0,t.listParticipantTranscript)(a.threadId,a.bot);await (0,r.runBot)({bot:a.bot,messages:(0,r.resumeTranscript)(g,await (0,t.listRoomReceipts)(a.threadId,a.bot,g))},{signal:b,threadId:a.threadId,parent:a.id,caller:a.caller,owner:f.bot,contextBudget:await (0,t.roomContextBudget)(a.threadId,a.bot),compactNow:()=>M.delete(N(a.threadId,a.bot)),session:(0,k.botBrowserSession)(a.threadId,a.bot),notes:()=>(0,t.consumeRoomInbox)(a),send:async c=>{b.throwIfAborted();let d=c.to.trim();if(d.toLowerCase()===u.ROOM_THURSDAY.toLowerCase())d=u.ROOM_THURSDAY;else{let a=await (0,q.findJobBot)(d);(!a||a.disabled)&&(0,n.publicError)(`No enabled bot named "${d}".`),d=a.name}let e=await (0,t.sendRoomMessage)(a,{...c,to:d});return z(a.threadId).catch(a=>m.logger.error("room message scheduling",a)),e},emit:async g=>{(!b.aborted||"tool-result"===g.type)&&(await c.on(g),"step"===g.type&&await (0,v.addThreadUsage)(a.threadId,g.usage,a.bot===f.bot?{tokens:g.usage.input,budget:g.budget}:null),"compact"===g.type&&await (0,v.addThreadUsage)(a.threadId,g.usage),"turn-end"===g.type&&(d=g),"error"===g.type&&(e={message:g.message,retry:g.retry},g.budget&&await (0,t.lowerRoomContextBudget)(a,g.budget)))}})}catch(c){b.aborted||(m.logger.error(`thread ${a.threadId}: ${a.bot} broke`,c),e={message:(0,g.modelErrorToString)(c),retry:!(0,n.isPublicError)(c)&&!(0,g.isProviderRefusal)(c)})}return{ending:d,failure:e}}class O{work;signal;lane;assistant;tool;parts;calls;results;constructor(a,b){this.work=a,this.signal=b,this.lane=(0,p.PromiseChain)(),this.assistant=null,this.tool=null,this.parts={assistant:[],tool:[]},this.calls=new Set,this.results=new Set}async write(a,b,c=!1){let d={bot:this.work.bot,parent:this.work.id,role:b.role,content:b.content,compact:c,note:c};return null===a?(0,t.appendRoomMessage)(this.work.threadId,d):(await (0,v.upsertMessage)(this.work.threadId,a,d),a)}on(a){return this.lane(async()=>{if(!this.signal.aborted||"tool-result"===a.type)if("text"===a.type)this.parts.assistant.push({type:"text",text:a.text}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant});else if("tool"===a.type){if(this.calls.has(a.id)){let b=this.parts.assistant.find(b=>"tool-call"===b.type&&b.toolCallId===a.id);b&&"tool-call"===b.type&&a.providerOptions&&(b.providerOptions=a.providerOptions,this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant}));return}this.calls.add(a.id),this.parts.assistant.push({type:"tool-call",toolCallId:a.id,toolName:a.name,input:a.input,...a.providerExecuted?{providerExecuted:!0}:{},...a.providerOptions?{providerOptions:a.providerOptions}:{}}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant})}else if("tool-result"===a.type){if(this.results.has(a.id))return;this.results.add(a.id),this.parts.tool.push({type:"tool-result",toolCallId:a.id,toolName:a.name,output:a.error?{type:"error-text",value:String(a.output)}:"string"==typeof a.output?{type:"text",value:a.output}:{type:"json",value:a.output}}),this.tool=await this.write(this.tool,{role:"tool",content:this.parts.tool})}else if("step"===a.type){let b=[this.assistant,this.tool];for(let[c,d]of a.messages.entries())await this.write(b[c]??null,d);let c=b.slice(a.messages.length).filter(a=>null!==a);c.length&&await (0,v.deleteMessages)(this.work.threadId,c),this.assistant=this.tool=null,this.parts={assistant:[],tool:[]}}else"compact"===a.type&&await this.write(null,{role:"user",content:a.text},!0)})}}async function C(a){let b=[...K.values()].filter(b=>b.threadId===a);for(let a of b)a.stop.abort();await Promise.all(b.map(a=>a.done))}async function D(a){await L(a,async()=>{let b=await (0,v.findThread)(a);b||(0,n.publicError)("No such thread."),b.endedAt&&(0,n.publicError)("That thread has already ended."),await (0,t.cancelRoom)(a),await (0,v.updateThread)(a,{status:"cancelled",outcome:null,pending:null,seen:!0,endedAt:new Date}),await C(a),await (0,k.closeJobShell)(a)})}async function E(a){return L(a,()=>F(a))}async function F(a){let b=await (0,v.findThread)(a);await (0,t.cancelRoom)(a),await C(a),await (0,k.removeJobBrowsers)(a);let c=await (0,v.deleteThread)(a);return c&&b&&await (0,k.removeJobScratch)(a,b.label),c}async function G(a){let b=a?.getTime(),c=a=>void 0===b||(a.endedAt??a.updatedAt).getTime()<b,d=0;for(let a of(await (0,v.listThreadFolders)()))("done"===a.status||"cancelled"===a.status)&&c(a)&&await L(a.id,async()=>{let b=await (0,v.findThread)(a.id);b?.status!=="done"&&b?.status!=="cancelled"||c(b)&&await F(a.id)&&(d+=1)});return d}async function H(){let a=Date.now()-f.WORKSPACE_KEEP.forMs,b=b=>("done"===b.status||"cancelled"===b.status)&&(b.endedAt??b.updatedAt).getTime()<a,c=new Set(await (0,k.listScratchFolders)()),d=[];for(let a of(await (0,v.listThreadFolders)())){let e=(0,k.jobScratch)(a.id,a.label);c.delete(e)&&b(a)&&await L(a.id,async()=>{let c=await (0,v.findThread)(a.id);c&&b(c)&&(await (0,k.closeHiddenBrowser)(a.id),await (0,k.removeJobScratch)(a.id,a.label),d.push(e))})}return d.push(...await (0,k.removeUnchangedFolders)([...c])),await (0,k.pruneJobFiles)(),d.length&&m.logger.info(`cleared ${d.length} old job folder(s): ${d.join(", ")}`),d}async function I(){for(let a of(await (0,v.listRunningThreadIds)()))await L(a,async()=>{[...K.values()].some(b=>b.threadId===a)||(await (0,v.findThread)(a))?.status==="running"&&await (0,t.pauseRoom)(a,"The server restarted. Resume from the saved conversation.")})}async function J(a){let b=await (0,v.listRunningThreadIds)();await Promise.all(b.map(b=>L(b,async()=>{(await (0,v.findThread)(b))?.status==="running"&&(await C(b),await (0,t.pauseRoom)(b,a))})))}a.s(["answerThread",0,y,"askCompact",0,function(a,b){M.add(N(a,b))},"cancelThread",0,D,"pauseThreads",0,J,"removeFinishedThreads",0,G,"removeThread",0,E,"startThread",0,x,"sweepJobFiles",0,H,"sweepThreads",0,I]),c()}catch(a){c(a)}},!1),317844,a=>a.a(async(b,c)=>{try{var d,e=a.i(106450),f=a.i(64203),g=a.i(569572),h=a.i(176668),i=a.i(182248),j=a.i(947950),k=a.i(899284),l=b([j]);[j]=l.then?(await l)():l;class m extends Error{serverName;authorizationUrl;constructor(a,b){super(`MCP server "${a}" requires authorization`),this.serverName=a,this.authorizationUrl=b,this.name="McpAuthRequiredError"}}class n{store;serverName;oauth;callbackUrl;clientName;lastAuthorizationUrl;constructor(a,b,c,d,e){this.store=a,this.serverName=b,this.oauth=c,this.callbackUrl=d,this.clientName=e}get redirectUrl(){return this.callbackUrl}get clientMetadata(){return{client_name:this.clientName,redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post"}}async persist(a){this.oauth={...this.oauth,...a},await this.store.saveOAuth(this.serverName,this.oauth)}clientInformation(){return this.oauth.clientInformation}async saveClientInformation(a){await this.persist({clientInformation:a})}tokens(){return this.oauth.tokens}async saveTokens(a){await this.persist({tokens:a})}authorizationServerInformation(){return this.oauth.authorizationServer}async saveAuthorizationServerInformation(a){await this.persist({authorizationServer:a})}codeVerifier(){if(!this.oauth.codeVerifier)throw Error("No code verifier saved");return this.oauth.codeVerifier}async saveCodeVerifier(a){await this.persist({codeVerifier:a})}state(){return crypto.randomUUID()}async saveState(a){await this.persist({state:a})}storedState(){return this.oauth.state}redirectToAuthorization(a){this.lastAuthorizationUrl=a}async invalidateCredentials(a){let b={...this.oauth};("all"===a||"client"===a)&&(b.clientInformation=void 0),("all"===a||"tokens"===a)&&(b.tokens=void 0),("all"===a||"verifier"===a)&&(b.codeVerifier=void 0),this.oauth=b,await this.store.saveOAuth(this.serverName,b)}}let o=globalThis;o.__thursdayMcpManager&&o.__thursdayMcpManager.dispose(),d={callbackUrl:new URL("/api/mcp/oauth/callback",g.APP_URL).href,clientName:g.APP_NAME},o.__thursdayMcpManager=new class a{store;sessions;connecting;callbackUrl;clientName;constructor(a,b){this.store=a,this.sessions=new Map,this.connecting=new Map,this.callbackUrl=b.callbackUrl,this.clientName=b.clientName??g.APP_NAME}async connect(a){let b=this.connecting.get(a);if(b)return b;let c=this.doConnect(a).finally(()=>this.connecting.delete(a));return this.connecting.set(a,c),c}async callTool(a,b,c,d){let f=await this.ensureClient(a);try{let e=await f.callTool({name:b,arguments:c,options:d?{signal:d}:void 0});return this.touch(a),e}catch(b){if(b instanceof e.UnauthorizedError)throw await this.closeSession(a),new m(a);throw b}}async finishAuthorization(a){let b=a.get("state"),c=a.get("code");if(!b||!c)throw Error("OAuth callback is missing code or state");let d=await this.store.findByOAuthState(b);if(!d||!(0,k.isRemoteConfig)(d.config))throw Error("No server is waiting for this authorization");let f=this.providerFor(d),g=await (0,e.auth)(f,{serverUrl:d.config.url,authorizationCode:c,callbackState:b});if("AUTHORIZED"!==g)throw Error(`Token exchange ended in "${g}"`);return await f.invalidateCredentials("verifier"),await this.connect(d.name),d.name}async disconnect(a){await this.closeSession(a)}async dispose(){await Promise.all([...this.sessions.keys()].map(a=>this.closeSession(a)))}async doConnect(a){await this.closeSession(a);let b=await this.store.load(a);if(!b)throw Error(`Unknown MCP server "${a}"`);let c={};try{let d=await this.openClient(b,c),e=(await d.listTools()).tools.map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,outputSchema:a.outputSchema}));return this.adopt(a,d),await this.store.saveConnectionResult(a,{toolInfo:e,lastError:null}),h.logger.info(`mcp "${a}" connected — ${e.length} tools`),{status:"connected",tools:e}}catch(l){var d,f;let g;if(l instanceof e.UnauthorizedError||l?.cause instanceof e.UnauthorizedError){let b=c.href;if(b)return await this.store.saveConnectionResult(a,{toolInfo:[],lastError:"Authorization required — finish sign-in in the opened tab"}),{status:"auth_required",authorizationUrl:b}}let j=(d=l,f=b,g=(0,i.errorToString)(d),(0,k.isRemoteConfig)(f.config)&&!f.oauth?.clientInformation&&/Invalid OAuth error response/.test(g)?`This server does not let an app register itself for sign-in, so it cannot be connected here. It answered: ${g}`:g);throw await this.store.saveConnectionResult(a,{toolInfo:[],lastError:j}),h.logger.warn(`mcp "${a}" failed — ${j}`),Error(j,{cause:l})}}async openClient(a,b={}){if((0,k.isRemoteConfig)(a.config)){let c=this.providerFor(a);try{return await (0,e.createMCPClient)({name:this.clientName,transport:{type:"http",url:a.config.url,headers:a.config.headers,authProvider:c,redirect:"follow"}})}finally{b.href=c.lastAuthorizationUrl?.href}}return(0,e.createMCPClient)({name:this.clientName,transport:new f.Experimental_StdioMCPTransport({command:a.config.command,args:a.config.args,env:a.config.env})})}providerFor(a){return new n(this.store,a.name,a.oauth??{},this.callbackUrl,this.clientName)}async ensureClient(a){let b=this.sessions.get(a);if(b)return b.client;let c=await this.connect(a);if("auth_required"===c.status)throw new m(a,c.authorizationUrl);let d=this.sessions.get(a);if(!d)throw Error(`Session for "${a}" vanished mid-connect`);return d.client}adopt(a,b){this.sessions.set(a,{client:b,idleTimer:this.armIdleTimer(a)})}touch(a){let b=this.sessions.get(a);b&&(clearTimeout(b.idleTimer),b.idleTimer=this.armIdleTimer(a))}armIdleTimer(a){let b=setTimeout(()=>{this.closeSession(a)},g.MCP_IDLE_MS);return b.unref?.(),b}async closeSession(a){let b=this.sessions.get(a);b&&(this.sessions.delete(a),clearTimeout(b.idleTimer),await b.client.close().catch(()=>{}))}}({load:a=>(0,j.findServer)(a),saveOAuth:(a,b)=>(0,j.saveOAuthData)(a,b),saveConnectionResult:(a,b)=>null===b.lastError?(0,j.syncServerTools)(a,b.toolInfo):(0,j.saveConnectionError)(a,b.lastError),findByOAuthState:a=>(0,j.findServerByOAuthState)(a)},d);let p=o.__thursdayMcpManager;a.s(["McpAuthRequiredError",0,m,"mcpManager",0,p]),c()}catch(a){c(a)}},!1),947950,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(351674),f=a.i(203469),g=a.i(184838),h=a.i(714428),i=a.i(899284),j=b([g]);async function k(a){var b;let[c]=await g.database.select({name:h.mcpServerTable.name,config:h.mcpServerTable.config,lastError:h.mcpServerTable.lastError,toolsSyncedAt:h.mcpServerTable.toolsSyncedAt}).from(h.mcpServerTable).where((0,d.eq)(h.mcpServerTable.name,a));return c?{...c,config:(b=c.config,(0,i.isRemoteConfig)(b)?{url:b.url}:{command:b.command,args:b.args}),tools:await l(a)}:null}async function l(a){return g.database.select({id:h.mcpToolTable.id,name:h.mcpToolTable.name,description:h.mcpToolTable.description,inputSchema:h.mcpToolTable.inputSchema,outputSchema:h.mcpToolTable.outputSchema}).from(h.mcpToolTable).where((0,d.eq)(h.mcpToolTable.serverName,a)).orderBy(h.mcpToolTable.name)}async function m(a){let[b]=await g.database.select().from(h.mcpServerTable).where((0,d.eq)(h.mcpServerTable.name,a));return b??null}[g]=j.then?(await j)():j;let u=()=>f.appEvents.emit({type:"mcp"});async function n(a){let[b]=await g.database.insert(h.mcpServerTable).values({...a,lastError:null}).onConflictDoUpdate({target:h.mcpServerTable.name,set:{config:a.config,lastError:null}}).returning();return u(),b}async function o(a,b){await g.database.transaction(async c=>{b.length&&await c.insert(h.mcpToolTable).values(b.map(b=>({...b,serverName:a}))).onConflictDoUpdate({target:[h.mcpToolTable.serverName,h.mcpToolTable.name],set:{description:p(h.mcpToolTable.description),inputSchema:p(h.mcpToolTable.inputSchema),outputSchema:p(h.mcpToolTable.outputSchema)}}),await c.delete(h.mcpToolTable).where(b.length?(0,d.and)((0,d.eq)(h.mcpToolTable.serverName,a),(0,d.notInArray)(h.mcpToolTable.name,b.map(a=>a.name))):(0,d.eq)(h.mcpToolTable.serverName,a)),await c.update(h.mcpServerTable).set({lastError:null,toolsSyncedAt:new Date}).where((0,d.eq)(h.mcpServerTable.name,a))}),u()}function p(a){return e.sql.raw(`excluded."${a.name}"`)}async function q(a,b){await g.database.update(h.mcpServerTable).set({lastError:b}).where((0,d.eq)(h.mcpServerTable.name,a)),u()}async function r(a,b){await g.database.update(h.mcpServerTable).set({oauth:b}).where((0,d.eq)(h.mcpServerTable.name,a)),u()}async function s(a){let[b]=await g.database.select().from(h.mcpServerTable).where(e.sql`json_extract(${h.mcpServerTable.oauth}, '$.state') = ${a}`);return b??null}async function t(a){let b=await g.database.delete(h.mcpServerTable).where((0,d.eq)(h.mcpServerTable.name,a)).returning();return b.length>0&&u(),b.length>0}a.s(["deleteServer",0,t,"findPinnedTools",0,function(a){return g.database.select({server:h.mcpToolTable.serverName,name:h.mcpToolTable.name,description:h.mcpToolTable.description,inputSchema:h.mcpToolTable.inputSchema}).from(h.botMcpToolTable).innerJoin(h.mcpToolTable,(0,d.eq)(h.botMcpToolTable.toolId,h.mcpToolTable.id)).where((0,d.eq)(h.botMcpToolTable.botName,a)).orderBy(h.mcpToolTable.serverName,h.mcpToolTable.name)},"findServer",0,m,"findServerByOAuthState",0,s,"findServerDetail",0,k,"findToolSchemas",0,function(a,b){return b.length?g.database.select({name:h.mcpToolTable.name,description:h.mcpToolTable.description,inputSchema:h.mcpToolTable.inputSchema}).from(h.mcpToolTable).where((0,d.and)((0,d.eq)(h.mcpToolTable.serverName,a),(0,d.inArray)(h.mcpToolTable.name,b))).orderBy(h.mcpToolTable.name):Promise.resolve([])},"listServerNames",0,function(){return g.database.select({name:h.mcpServerTable.name}).from(h.mcpServerTable).orderBy(h.mcpServerTable.name)},"listToolNames",0,function(a){let b=g.database.select({server:h.mcpToolTable.serverName,name:h.mcpToolTable.name}).from(h.mcpToolTable);return a?b.where((0,d.eq)(h.mcpToolTable.serverName,a)).orderBy(h.mcpToolTable.name):b.orderBy(h.mcpToolTable.serverName,h.mcpToolTable.name)},"saveConnectionError",0,q,"saveOAuthData",0,r,"syncServerTools",0,o,"upsertServer",0,n]),c()}catch(a){c(a)}},!1),899284,a=>{"use strict";var b=a.i(53112),c=a.i(706210);let d=b.z.object({url:b.z.url(),headers:b.z.record(b.z.string(),b.z.string()).optional()}),e=b.z.object({command:b.z.string().min(1),args:b.z.array(b.z.string()).optional(),env:b.z.record(b.z.string(),b.z.string()).optional()}),f=b.z.union([d,e]),g=b.z.object({name:b.z.string(),description:b.z.string().optional(),inputSchema:b.z.looseObject({}).optional(),outputSchema:b.z.looseObject({}).optional()});b.z.object({clientInformation:b.z.looseObject({}).optional(),tokens:b.z.looseObject({}).optional(),authorizationServer:b.z.looseObject({}).optional(),codeVerifier:b.z.string().optional(),state:b.z.string().optional()});let h=b.z.object({name:b.z.string().min(1).max(40),config:f,toolCount:b.z.number().int(),lastError:b.z.string().nullish()}),i=g.extend({id:b.z.number().int(),description:b.z.string().nullish()});h.omit({toolCount:!0}).extend({tools:i.array().default([]),toolsSyncedAt:c.DateLikeSchema});let j=b.z.object({name:b.z.string().min(1,"Name is required").max(40).regex(/^[a-zA-Z0-9_-]+$/,"Only letters, numbers, - and _ are allowed"),config:f});b.z.union([b.z.object({mcpServers:b.z.record(b.z.string(),f)}),b.z.record(b.z.string(),f)]),a.s(["MCPServerFormSchema",0,j,"isRemoteConfig",0,function(a){return"url"in a}])},986743,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(530385),f=a.i(351674),g=a.i(203469);a.i(569572);var h=a.i(184838),i=a.i(714428),j=a.i(661210),k=b([h]);[h]=k.then?(await k)():k;let B=()=>g.appEvents.emit({type:"memory"});async function l(a,b,c={}){let[d]=await h.database.insert(i.memoryNoteTable).values({path:a,description:b,ownedByUser:c.ownedByUser??!1}).onConflictDoNothing({target:i.memoryNoteTable.path}).returning();return d&&B(),d??null}async function m(a,b){let[c]=await h.database.update(i.memoryNoteTable).set({...b,updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,a)).returning();return c&&B(),c??null}async function n(a){let b=await h.database.delete(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.id,a)).returning({id:i.memoryNoteTable.id});return b.length>0&&B(),b.length>0}async function o(a,b){let[c]=await h.database.insert(i.memoryFactTable).values({noteId:a,text:b,source:"user"}).returning();return await r(a),B(),c}async function p(a,b,c){let e=await h.database.transaction(async e=>{let f=await e.update(i.memoryFactTable).set({isLatest:!1}).where((0,d.and)((0,d.eq)(i.memoryFactTable.id,b),(0,d.eq)(i.memoryFactTable.noteId,a),(0,d.eq)(i.memoryFactTable.isLatest,!0))).returning({id:i.memoryFactTable.id});if(0===f.length)return null;let[g]=await e.insert(i.memoryFactTable).values({noteId:a,text:c,source:"user"}).returning();return await e.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,a)),g});return e&&B(),e}async function q(a,b){let c=await h.database.delete(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.id,b),(0,d.eq)(i.memoryFactTable.noteId,a))).returning({id:i.memoryFactTable.id});return c.length>0&&(await r(a),B()),c.length>0}function r(a){return h.database.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,a))}async function s(){for(let a of j.MEMORY_ALWAYS_LISTED){let b=j.MEMORY_PATHS.find(b=>b.path===a)?.of??a;await h.database.insert(i.memoryNoteTable).values({path:a,description:b}).onConflictDoUpdate({target:i.memoryNoteTable.path,set:{description:b}})}}async function t(a,b={}){let c=[...new Set(a.map(a=>a.trim()).filter(Boolean))];if(!c.length)return{notes:[],missing:[]};let g=await h.database.select({id:i.memoryNoteTable.id,path:i.memoryNoteTable.path,description:i.memoryNoteTable.description}).from(i.memoryNoteTable).where((0,d.inArray)(i.memoryNoteTable.path,c)),j=new Map(g.map(a=>[a.path,a])),k=c.filter(a=>!j.has(a));if(!g.length)return{notes:[],missing:k};let l=g.map(a=>a.id),m=await h.database.select({id:i.memoryFactTable.id,noteId:i.memoryFactTable.noteId,text:i.memoryFactTable.text,source:i.memoryFactTable.source,createdAt:i.memoryFactTable.createdAt,saidAt:i.callTable.startedAt}).from(i.memoryFactTable).leftJoin(i.callTable,(0,d.eq)(i.memoryFactTable.callId,i.callTable.id)).where((0,d.and)((0,d.eq)(i.memoryFactTable.isLatest,!0),(0,d.inArray)(i.memoryFactTable.noteId,l))).orderBy((0,e.asc)(i.memoryFactTable.id));return!1!==b.touch&&await h.database.update(i.memoryNoteTable).set({hits:f.sql`${i.memoryNoteTable.hits} + 1`,lastReadAt:new Date}).where((0,d.inArray)(i.memoryNoteTable.id,l)),{notes:c.flatMap(a=>{let b=j.get(a);return b?[{path:b.path,description:b.description,facts:m.filter(a=>a.noteId===b.id).map(a=>({id:a.id,text:a.text,...a.saidAt?{saidAt:a.saidAt}:{}}))}]:[]}),missing:k}}(0,d.inArray)(i.memoryNoteTable.path,j.MEMORY_ALWAYS_LISTED);let C=a=>a.toLowerCase().replace(/[\s.,!?…·'"`]/g,"");async function u(a,b,c,e,f){let g=await a.select({id:i.memoryFactTable.id,text:i.memoryFactTable.text}).from(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.noteId,b),(0,d.eq)(i.memoryFactTable.isLatest,!0))),h=new Map(g.map(a=>[C(a.text),a]));for(let g of c){let c=g.text.trim();if(!c)continue;if(null!=g.replaces){let[j]=await a.select({id:i.memoryFactTable.id,text:i.memoryFactTable.text}).from(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.id,g.replaces),(0,d.eq)(i.memoryFactTable.noteId,b),(0,d.eq)(i.memoryFactTable.isLatest,!0)));if(j){if(C(j.text)===C(c))continue;await a.update(i.memoryFactTable).set({isLatest:!1}).where((0,d.eq)(i.memoryFactTable.id,j.id)),h.delete(C(j.text));let[g]=await a.insert(i.memoryFactTable).values({noteId:b,text:c,source:e,callId:f}).returning({id:i.memoryFactTable.id});h.set(C(c),{...g,text:c});continue}}if(h.has(C(c)))continue;let[j]=await a.insert(i.memoryFactTable).values({noteId:b,text:c,source:e,callId:f}).returning({id:i.memoryFactTable.id});h.set(C(c),{...j,text:c})}await a.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,b))}async function v(a,b,c,e=null){let f=a.trim();if(!await h.database.transaction(async a=>{let[g]=await a.select({id:i.memoryNoteTable.id}).from(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.path,f));return!!g&&(await u(a,g.id,b,c,e),!0)}))return null;let{notes:g}=await t([f],{touch:!1});return B(),g[0]??null}async function w(a,b,c,d,e=null){let f=a.trim();if(!await h.database.transaction(async a=>{let[g]=await a.insert(i.memoryNoteTable).values({path:f,description:b}).onConflictDoNothing({target:i.memoryNoteTable.path}).returning({id:i.memoryNoteTable.id});return!!g&&(await u(a,g.id,c,d,e),!0)}))return null;let{notes:g}=await t([f],{touch:!1});return B(),g[0]??null}async function x(a,b){let[c]=await h.database.update(i.memoryNoteTable).set({description:b,updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.path,a.trim())).returning({id:i.memoryNoteTable.id});return c&&B(),!!c}async function y(){let[a,b]=await Promise.all([h.database.select({id:i.memoryNoteTable.id,path:i.memoryNoteTable.path,description:i.memoryNoteTable.description,hits:i.memoryNoteTable.hits,lastReadAt:i.memoryNoteTable.lastReadAt,createdAt:i.memoryNoteTable.createdAt}).from(i.memoryNoteTable),h.database.select({noteId:i.memoryFactTable.noteId,count:f.sql`count(*)`}).from(i.memoryFactTable).where((0,d.eq)(i.memoryFactTable.isLatest,!0)).groupBy(i.memoryFactTable.noteId)]),c=new Map(b.map(a=>[a.noteId,a.count]));return a.filter(a=>(0,j.isAlwaysListed)(a.path)||(c.get(a.id)??0)>0).sort((a,b)=>Number((0,j.isAlwaysListed)(b.path))-Number((0,j.isAlwaysListed)(a.path))||(0,j.recallScore)(b)-(0,j.recallScore)(a)).map(a=>({path:a.path,description:a.description,factCount:c.get(a.id)??0,lastSeenAt:a.lastReadAt??a.createdAt}))}async function z(a){let b=await h.database.transaction(async b=>{let c=await b.delete(i.memoryFactTable).where((0,d.eq)(i.memoryFactTable.id,a)).returning({noteId:i.memoryFactTable.noteId});if(0===c.length)return null;let e=c[0].noteId,[g]=await b.select({path:i.memoryNoteTable.path,ownedByUser:i.memoryNoteTable.ownedByUser}).from(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.id,e)),[h]=await b.select({count:f.sql`count(*)`}).from(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.noteId,e),(0,d.eq)(i.memoryFactTable.isLatest,!0)));return h?.count!==0||!g||g.ownedByUser||(0,j.isAlwaysListed)(g.path)?(await b.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,e)),{path:g?.path??"",noteGone:!1}):(await b.delete(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.id,e)),{path:g.path,noteGone:!0})});return b&&B(),b}async function A(){let a=await h.database.delete(i.memoryNoteTable).returning({id:i.memoryNoteTable.id});return await s(),a.length>0&&B(),a.length}a.s(["addFact",0,o,"createNote",0,l,"createNoteWithFacts",0,w,"deleteAllNotes",0,A,"deleteNote",0,n,"describeNote",0,x,"forgetFact",0,q,"forgetFactById",0,z,"listNoteIndex",0,y,"readNotes",0,t,"reviseFact",0,p,"updateNote",0,m,"writeFacts",0,v]),c()}catch(a){c(a)}},!1),661210,a=>{"use strict";var b=a.i(53112),c=a.i(569572),d=a.i(706210);let e=b.z.enum(["user","call","bot"]),f=b.z.string().trim().min(1,"A note needs a line saying what it is about").max(c.MEMORY_LIMITS.descriptionChars,`A note's line is one line: at most ${c.MEMORY_LIMITS.descriptionChars} characters`),g=b.z.object({id:b.z.number(),text:b.z.string(),source:e.nullish(),createdAt:d.DateLikeSchema});b.z.object({id:b.z.number(),path:b.z.string(),description:b.z.string(),ownedByUser:b.z.boolean(),hits:b.z.number(),lastReadAt:d.DateLikeSchema.nullable(),createdAt:d.DateLikeSchema,updatedAt:d.DateLikeSchema,factCount:b.z.number(),facts:g.array()});let h=[{path:"profile",of:"The user themselves — name, age, what they do, where they live, whatever else says who they are"},{path:"preferences",of:"How they want things done, and said — read whole on every call, so a rule for a particular situation goes here too"},{path:"people/",of:"Someone in their life, and what matters about them"},{path:"projects/",of:"Something with an end — a trip, a purchase, a deadline, a thing being built"},{path:"topics/",of:"Something ongoing that keeps coming back"}],i=h.filter(a=>!a.path.endsWith("/")).map(a=>a.path),j=h.filter(a=>a.path.endsWith("/")).map(a=>a.path.slice(0,-1)),k=RegExp(`^(?:${i.join("|")}|(?:${j.join("|")})/.+)$`);a.s(["MEMORY_ALWAYS_LISTED",0,i,"MEMORY_PATHS",0,h,"NoteLineSchema",0,f,"isAlwaysListed",0,a=>i.includes(a),"isMemoryPath",0,a=>k.test(a),"recallScore",0,function(a){let b=(0,d.toDate)(a.lastReadAt??a.createdAt),c=Math.max(0,(Date.now()-b.getTime())/864e5);return(a.hits+1)/(1+c)}])},780946,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(258261),f=a.i(530385),g=a.i(203469),h=a.i(569572),i=a.i(184838),j=a.i(714428),k=a.i(221214),l=a.i(293480),m=a.i(643020),n=b([i,k]);[i,k]=n.then?(await n)():n;let z=()=>g.appEvents.emit({type:"routines"});async function o(a,b){return i.database.select({id:j.threadTable.id,status:j.threadTable.status,outcome:j.threadTable.outcome,updatedAt:j.threadTable.updatedAt}).from(j.threadTable).where((0,d.eq)(j.threadTable.routineId,a)).orderBy((0,f.desc)(j.threadTable.createdAt)).limit(b)}let A=async a=>{let{createdAt:b,...c}=a;return{...c,runs:await o(a.id,h.ROUTINE.runsShown)}};async function p(){let a=await i.database.select().from(j.routineTable).orderBy(j.routineTable.createdAt);return Promise.all(a.map(A))}async function q(a){let[b]=await i.database.select().from(j.routineTable).where((0,d.eq)(j.routineTable.id,a));return b?A(b):null}async function r(a){let b=await q(a.trim());if(b)return b;let c=a.trim().toLowerCase(),d=(await p()).filter(a=>a.label.toLowerCase()===c);return 1===d.length?d[0]:null}async function s(a){let b=await (0,k.findJobBot)(a);return(!b||b.disabled)&&(0,l.publicError)("Choose an enabled bot."),b.name}function t(a,b){b&&"once"===a.kind&&(0,m.momentOf)(a.at)<=new Date&&(0,l.publicError)("That time has passed. Pick a later one.")}async function u(a){let[{total:b}]=await i.database.select({total:(0,e.count)()}).from(j.routineTable);b>=h.ROUTINE.max&&(0,l.publicError)(`There are already ${h.ROUTINE.max} routines. Delete one to make another.`),t(a.schedule,!0);let[c]=await i.database.insert(j.routineTable).values({id:crypto.randomUUID(),...a,bot:await s(a.bot),nextRunAt:(0,m.nextRun)(a.schedule,new Date)}).returning();return z(),A(c)}async function v(a,b){let[c]=await i.database.select().from(j.routineTable).where((0,d.eq)(j.routineTable.id,a));if(!c)return null;let e=b.schedule??c.schedule,f=!!b.schedule||b.enabled&&!c.enabled;f&&t(e,b.enabled??c.enabled);let[g]=await i.database.update(j.routineTable).set({...b,...b.bot?{bot:await s(b.bot)}:{},...f?{nextRunAt:(0,m.nextRun)(e,new Date)}:{}}).where((0,d.eq)(j.routineTable.id,a)).returning();return z(),A(g)}async function w(a){let b=await i.database.delete(j.routineTable).where((0,d.eq)(j.routineTable.id,a)).returning({id:j.routineTable.id});return b.length&&z(),b.length>0}async function x(a){return(await o(a,1))[0]??null}async function y(a){return(await i.database.select({id:j.threadTable.id}).from(j.threadTable).where((0,d.and)((0,d.eq)(j.threadTable.routineId,a),(0,d.eq)(j.threadTable.seen,!1),(0,d.inArray)(j.threadTable.status,["done","cancelled"])))).map(a=>a.id)}a.s(["createRoutine",0,u,"deleteRoutine",0,w,"findRoutine",0,q,"latestRun",0,x,"listRoutines",0,p,"listUnseenRunIds",0,y,"resolveRoutine",0,r,"updateRoutine",0,v]),c()}catch(a){c(a)}},!1),643020,a=>{"use strict";var b=a.i(723885),c=a.i(569572),d=a.i(706210);let e=b.default.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"A time is HH:MM, 00:00 to 23:59");function f(a){let[b,c]=a.split(" "),[d,e,f]=b.split("-").map(Number),[g,h]=c.split(":").map(Number);return new Date(d,e-1,f,g,h)}let g=/^\d{4}-\d\d-\d\d ([01]\d|2[0-3]):[0-5]\d$/,h=b.default.string().regex(g,'A moment is "YYYY-MM-DD HH:MM"').refine(a=>{if(!g.test(a))return!0;let b=f(a);return b.getMonth()===Number(a.slice(5,7))-1&&b.getDate()===Number(a.slice(8,10))},"There is no such day"),i=b.default.discriminatedUnion("kind",[b.default.object({kind:b.default.literal("once"),at:h}),b.default.object({kind:b.default.literal("daily"),time:e,days:b.default.array(b.default.number().int().min(1).max(7)).min(1,"Pick at least one day").transform(a=>[...new Set(a)].sort((a,b)=>a-b))}),b.default.object({kind:b.default.literal("every"),hours:b.default.number().int().min(c.ROUTINE.minHours,`No more often than every ${c.ROUTINE.minHours}h`).max(168)})]),j=b.default.object({bot:b.default.string().trim().min(1,"Pick a bot"),label:b.default.string().trim().min(1,"Give it a name").max(80),request:b.default.string().trim().min(1,"Say what it should do"),schedule:i}),k=b.default.object({id:b.default.string(),status:b.default.enum(["running","waiting","done","cancelled"]),outcome:b.default.string().nullable(),updatedAt:d.DateLikeSchema});j.extend({id:b.default.string(),enabled:b.default.boolean(),nextRunAt:d.DateLikeSchema,runs:b.default.array(k)});let l=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],m=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];a.s(["RoutineInputSchema",0,j,"RoutineScheduleSchema",0,i,"momentOf",0,f,"nextRun",0,function(a,b){if("once"===a.kind)return f(a.at);if("every"===a.kind)return new Date(b.getTime()+36e5*a.hours);let[c,d]=a.time.split(":").map(Number);for(let e=0;e<=7;e++){let f=new Date(b);f.setDate(f.getDate()+e),f.setHours(c,d,0,0);let g=0===f.getDay()?7:f.getDay();if(f>b&&a.days.includes(g))return f}return new Date(b.getTime()+864e5)},"scheduleText",0,function(a){if("once"===a.kind){let[b,c]=a.at.split(" "),[,d,e]=b.split("-").map(Number);return`Once \xb7 ${m[d-1]} ${e} ${c}`}if("every"===a.kind)return 1===a.hours?"Every hour":`Every ${a.hours} hours`;let{days:b,time:c}=a;if(7===b.length)return`Daily ${c}`;if(1===b.length)return`${l[b[0]-1]} ${c}`;let d=b.every((a,c)=>0===c||a===b[c-1]+1)?`${l[b[0]-1]}–${l[b.at(-1)-1]}`:b.map(a=>l[a-1]).join(" ");return`Daily ${c} \xb7 ${d}`}])},487591,422807,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(203469),e=a.i(569572),f=a.i(821415);a.i(176668);let g=a=>a.trim().toLowerCase().replace(/^[a-z]+:\/\//,"").replace(/^www\./,"").replace(/[/?#].*$/,"");a.s(["siteOf",0,g],422807);let h=(0,c.join)(e.DATA_DIR,e.PATHS.signIns),i=a=>(0,c.join)(h,`${encodeURIComponent(g(a))}.json`),j=()=>d.appEvents.emit({type:"signins"});async function k(a){try{return JSON.parse(await (0,b.readFile)(i(a),"utf8"))}catch{return null}}async function l(a){let b=g(a),c=await k(b);if(c)return c;let d=(await n()).map(a=>a.site).filter(a=>b.endsWith(`.${a}`)).sort((a,b)=>b.length-a.length)[0];return d?k(d):null}async function m(a){await (0,b.mkdir)(h,{recursive:!0}),await (0,b.writeFile)(i(a.site),JSON.stringify(a),{mode:384}),j()}async function n(){let a=await (0,b.readdir)(h).catch(()=>[]);return(await Promise.all(a.filter(a=>a.endsWith(".json")).map(a=>k(decodeURIComponent(a.slice(0,-5)))))).flatMap(a=>a?[(({state:a,...b})=>b)(a)]:[]).sort((a,b)=>a.site.localeCompare(b.site))}async function o(a){let b=await l(a.site);if(b&&!b.bots.includes(a.bot)){let c=b.asking.includes(a.bot)?b:{...b,asking:[...b.asking,a.bot]};return c!==b&&await m(c),{kind:"taken",signIn:(({state:a,...b})=>b)(c)}}let c=b?.site??g(a.site),d={site:c,account:a.account.trim()||c,bots:[...new Set([...b?.bots??[],a.bot])],asking:(b?.asking??[]).filter(b=>b!==a.bot),keptAt:new Date().toISOString(),usedAt:b?.usedAt??null,state:a.state};return await m(d),{kind:"kept",signIn:(({state:a,...b})=>b)(d)}}let p=globalThis.__signInsHeld??=new Map;async function q(a,b){let c=await l(a);if(!c)return{kind:"none",kept:(await n()).map(a=>a.site)};if(!c.bots.includes(b))return c.asking.includes(b)||await m({...c,asking:[...c.asking,b]}),{kind:"ask",signIn:(({state:a,...b})=>b)(c)};let d={...c,usedAt:new Date().toISOString()};return await m(d),{kind:"state",signIn:(({state:a,...b})=>b)(d),state:c.state}}async function r(a,b){return(await (0,f.listBrowsers)(a,b)).find(a=>a.name===b.PLAYWRIGHT_CLI_SESSION)??null}async function s(a,b){let c=await r(a,b);return c?c.attached?"theirs":"own":null}async function t(a,b){let c=await r(a,b);return!!c&&!c.attached&&!0===c.headed}let u=a=>`${a.name}
|
|
131
|
+
Coordinator: ${f.bot}. Continue as ${a.bot} in this thread.`,hidden:!0}),await (0,t.consumeRoomInbox)(a);let g=await (0,t.listParticipantTranscript)(a.threadId,a.bot);await (0,r.runBot)({bot:a.bot,messages:(0,r.resumeTranscript)(g,await (0,t.listRoomReceipts)(a.threadId,a.bot,g))},{signal:b,threadId:a.threadId,parent:a.id,caller:a.caller,owner:f.bot,contextBudget:await (0,t.roomContextBudget)(a.threadId,a.bot),compactNow:()=>M.delete(N(a.threadId,a.bot)),session:(0,k.botBrowserSession)(a.threadId,a.bot),notes:()=>(0,t.consumeRoomInbox)(a),send:async c=>{b.throwIfAborted();let d=c.to.trim();if(d.toLowerCase()===u.ROOM_THURSDAY.toLowerCase())d=u.ROOM_THURSDAY;else{let a=await (0,q.findJobBot)(d);(!a||a.disabled)&&(0,n.publicError)(`No enabled bot named "${d}".`),d=a.name}let e=await (0,t.sendRoomMessage)(a,{...c,to:d});return z(a.threadId).catch(a=>m.logger.error("room message scheduling",a)),e},emit:async g=>{(!b.aborted||"tool-result"===g.type)&&(await c.on(g),"step"===g.type&&await (0,v.addThreadUsage)(a.threadId,g.usage,a.bot===f.bot?{tokens:g.usage.input,budget:g.budget}:null),"compact"===g.type&&await (0,v.addThreadUsage)(a.threadId,g.usage),"turn-end"===g.type&&(d=g),"error"===g.type&&(e={message:g.message,retry:g.retry},g.budget&&await (0,t.lowerRoomContextBudget)(a,g.budget)))}})}catch(c){b.aborted||(m.logger.error(`thread ${a.threadId}: ${a.bot} broke`,c),e={message:(0,g.modelErrorToString)(c),retry:!(0,n.isPublicError)(c)&&!(0,g.isProviderRefusal)(c)})}return{ending:d,failure:e}}class O{work;signal;lane;assistant;tool;parts;calls;results;constructor(a,b){this.work=a,this.signal=b,this.lane=(0,p.PromiseChain)(),this.assistant=null,this.tool=null,this.parts={assistant:[],tool:[]},this.calls=new Set,this.results=new Set}async write(a,b,c=!1){let d={bot:this.work.bot,parent:this.work.id,role:b.role,content:b.content,compact:c,note:c};return null===a?(0,t.appendRoomMessage)(this.work.threadId,d):(await (0,v.upsertMessage)(this.work.threadId,a,d),a)}on(a){return this.lane(async()=>{if(!this.signal.aborted||"tool-result"===a.type)if("text"===a.type)this.parts.assistant.push({type:"text",text:a.text}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant});else if("tool"===a.type){if(this.calls.has(a.id)){let b=this.parts.assistant.find(b=>"tool-call"===b.type&&b.toolCallId===a.id);b&&"tool-call"===b.type&&a.providerOptions&&(b.providerOptions=a.providerOptions,this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant}));return}this.calls.add(a.id),this.parts.assistant.push({type:"tool-call",toolCallId:a.id,toolName:a.name,input:a.input,...a.providerExecuted?{providerExecuted:!0}:{},...a.providerOptions?{providerOptions:a.providerOptions}:{}}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant})}else if("tool-result"===a.type){if(this.results.has(a.id))return;this.results.add(a.id),this.parts.tool.push({type:"tool-result",toolCallId:a.id,toolName:a.name,output:a.error?{type:"error-text",value:String(a.output)}:"string"==typeof a.output?{type:"text",value:a.output}:{type:"json",value:a.output}}),this.tool=await this.write(this.tool,{role:"tool",content:this.parts.tool})}else if("step"===a.type){let b=[this.assistant,this.tool];for(let[c,d]of a.messages.entries())await this.write(b[c]??null,d);let c=b.slice(a.messages.length).filter(a=>null!==a);c.length&&await (0,v.deleteMessages)(this.work.threadId,c),this.assistant=this.tool=null,this.parts={assistant:[],tool:[]}}else"compact"===a.type&&await this.write(null,{role:"user",content:a.text},!0)})}}async function C(a){let b=[...K.values()].filter(b=>b.threadId===a);for(let a of b)a.stop.abort();await Promise.all(b.map(a=>a.done))}async function D(a){await L(a,async()=>{let b=await (0,v.findThread)(a);b||(0,n.publicError)("No such thread."),b.endedAt&&(0,n.publicError)("That thread has already ended."),await (0,t.cancelRoom)(a),await (0,v.updateThread)(a,{status:"cancelled",outcome:null,pending:null,seen:!0,endedAt:new Date}),await C(a),await (0,k.closeJobShell)(a)})}async function E(a){return L(a,()=>F(a))}async function F(a){let b=await (0,v.findThread)(a);await (0,t.cancelRoom)(a),await C(a),await (0,k.removeJobBrowsers)(a);let c=await (0,v.deleteThread)(a);return c&&b&&await (0,k.removeJobScratch)(a,b.label),c}async function G(a){let b=a?.getTime(),c=a=>void 0===b||(a.endedAt??a.updatedAt).getTime()<b,d=0;for(let a of(await (0,v.listThreadFolders)()))("done"===a.status||"cancelled"===a.status)&&c(a)&&await L(a.id,async()=>{let b=await (0,v.findThread)(a.id);b?.status!=="done"&&b?.status!=="cancelled"||c(b)&&await F(a.id)&&(d+=1)});return d}async function H(){let a=Date.now()-f.WORKSPACE_KEEP.forMs,b=b=>("done"===b.status||"cancelled"===b.status)&&(b.endedAt??b.updatedAt).getTime()<a,c=new Set(await (0,k.listScratchFolders)()),d=[];for(let a of(await (0,v.listThreadFolders)())){let e=(0,k.jobScratch)(a.id,a.label);c.delete(e)&&b(a)&&await L(a.id,async()=>{let c=await (0,v.findThread)(a.id);c&&b(c)&&(await (0,k.closeHiddenBrowser)(a.id),await (0,k.removeJobScratch)(a.id,a.label),d.push(e))})}return d.push(...await (0,k.removeUnchangedFolders)([...c])),await (0,k.pruneJobFiles)(),d.length&&m.logger.info(`cleared ${d.length} old job folder(s): ${d.join(", ")}`),d}async function I(){for(let a of(await (0,v.listRunningThreadIds)()))await L(a,async()=>{[...K.values()].some(b=>b.threadId===a)||(await (0,v.findThread)(a))?.status==="running"&&await (0,t.pauseRoom)(a,"The server restarted. Resume from the saved conversation.")})}async function J(a){let b=await (0,v.listRunningThreadIds)();await Promise.all(b.map(b=>L(b,async()=>{(await (0,v.findThread)(b))?.status==="running"&&(await C(b),await (0,t.pauseRoom)(b,a))})))}a.s(["answerThread",0,y,"askCompact",0,function(a,b){M.add(N(a,b))},"cancelThread",0,D,"pauseThreads",0,J,"removeFinishedThreads",0,G,"removeThread",0,E,"startThread",0,x,"sweepJobFiles",0,H,"sweepThreads",0,I]),c()}catch(a){c(a)}},!1),317844,a=>a.a(async(b,c)=>{try{var d,e=a.i(106450),f=a.i(64203),g=a.i(569572),h=a.i(176668),i=a.i(182248),j=a.i(947950),k=a.i(899284),l=b([j]);[j]=l.then?(await l)():l;class m extends Error{serverName;authorizationUrl;constructor(a,b){super(`MCP server "${a}" requires authorization`),this.serverName=a,this.authorizationUrl=b,this.name="McpAuthRequiredError"}}class n{store;serverName;oauth;callbackUrl;clientName;lastAuthorizationUrl;constructor(a,b,c,d,e){this.store=a,this.serverName=b,this.oauth=c,this.callbackUrl=d,this.clientName=e}get redirectUrl(){return this.callbackUrl}get clientMetadata(){return{client_name:this.clientName,redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post"}}async persist(a){this.oauth={...this.oauth,...a},await this.store.saveOAuth(this.serverName,this.oauth)}clientInformation(){return this.oauth.clientInformation}async saveClientInformation(a){await this.persist({clientInformation:a})}tokens(){return this.oauth.tokens}async saveTokens(a){await this.persist({tokens:a})}authorizationServerInformation(){return this.oauth.authorizationServer}async saveAuthorizationServerInformation(a){await this.persist({authorizationServer:a})}codeVerifier(){if(!this.oauth.codeVerifier)throw Error("No code verifier saved");return this.oauth.codeVerifier}async saveCodeVerifier(a){await this.persist({codeVerifier:a})}state(){return crypto.randomUUID()}async saveState(a){await this.persist({state:a})}storedState(){return this.oauth.state}redirectToAuthorization(a){this.lastAuthorizationUrl=a}async invalidateCredentials(a){let b={...this.oauth};("all"===a||"client"===a)&&(b.clientInformation=void 0),("all"===a||"tokens"===a)&&(b.tokens=void 0),("all"===a||"verifier"===a)&&(b.codeVerifier=void 0),this.oauth=b,await this.store.saveOAuth(this.serverName,b)}}let o=globalThis;o.__thursdayMcpManager&&o.__thursdayMcpManager.dispose(),d={callbackUrl:new URL("/api/mcp/oauth/callback",g.APP_URL).href,clientName:g.APP_NAME},o.__thursdayMcpManager=new class a{store;sessions;connecting;callbackUrl;clientName;constructor(a,b){this.store=a,this.sessions=new Map,this.connecting=new Map,this.callbackUrl=b.callbackUrl,this.clientName=b.clientName??g.APP_NAME}async connect(a){let b=this.connecting.get(a);if(b)return b;let c=this.doConnect(a).finally(()=>this.connecting.delete(a));return this.connecting.set(a,c),c}async callTool(a,b,c,d){let f=await this.ensureClient(a);try{let e=await f.callTool({name:b,arguments:c,options:d?{signal:d}:void 0});return this.touch(a),e}catch(b){if(b instanceof e.UnauthorizedError)throw await this.closeSession(a),new m(a);throw b}}async finishAuthorization(a){let b=a.get("state"),c=a.get("code");if(!b||!c)throw Error("OAuth callback is missing code or state");let d=await this.store.findByOAuthState(b);if(!d||!(0,k.isRemoteConfig)(d.config))throw Error("No server is waiting for this authorization");let f=this.providerFor(d),g=await (0,e.auth)(f,{serverUrl:d.config.url,authorizationCode:c,callbackState:b});if("AUTHORIZED"!==g)throw Error(`Token exchange ended in "${g}"`);return await f.invalidateCredentials("verifier"),await this.connect(d.name),d.name}async disconnect(a){await this.closeSession(a)}async dispose(){await Promise.all([...this.sessions.keys()].map(a=>this.closeSession(a)))}async doConnect(a){await this.closeSession(a);let b=await this.store.load(a);if(!b)throw Error(`Unknown MCP server "${a}"`);let c={};try{let d=await this.openClient(b,c),e=(await d.listTools()).tools.map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,outputSchema:a.outputSchema}));return this.adopt(a,d),await this.store.saveConnectionResult(a,{toolInfo:e,lastError:null}),h.logger.info(`mcp "${a}" connected — ${e.length} tools`),{status:"connected",tools:e}}catch(l){var d,f;let g;if(l instanceof e.UnauthorizedError||l?.cause instanceof e.UnauthorizedError){let b=c.href;if(b)return await this.store.saveConnectionResult(a,{toolInfo:[],lastError:"Authorization required — finish sign-in in the opened tab"}),{status:"auth_required",authorizationUrl:b}}let j=(d=l,f=b,g=(0,i.errorToString)(d),(0,k.isRemoteConfig)(f.config)&&!f.oauth?.clientInformation&&/Invalid OAuth error response/.test(g)?`This server does not let an app register itself for sign-in, so it cannot be connected here. It answered: ${g}`:g);throw await this.store.saveConnectionResult(a,{toolInfo:[],lastError:j}),h.logger.warn(`mcp "${a}" failed — ${j}`),Error(j,{cause:l})}}async openClient(a,b={}){if((0,k.isRemoteConfig)(a.config)){let c=this.providerFor(a);try{return await (0,e.createMCPClient)({name:this.clientName,transport:{type:"http",url:a.config.url,headers:a.config.headers,authProvider:c,redirect:"follow"}})}finally{b.href=c.lastAuthorizationUrl?.href}}return(0,e.createMCPClient)({name:this.clientName,transport:new f.Experimental_StdioMCPTransport({command:a.config.command,args:a.config.args,env:a.config.env})})}providerFor(a){return new n(this.store,a.name,a.oauth??{},this.callbackUrl,this.clientName)}async ensureClient(a){let b=this.sessions.get(a);if(b)return b.client;let c=await this.connect(a);if("auth_required"===c.status)throw new m(a,c.authorizationUrl);let d=this.sessions.get(a);if(!d)throw Error(`Session for "${a}" vanished mid-connect`);return d.client}adopt(a,b){this.sessions.set(a,{client:b,idleTimer:this.armIdleTimer(a)})}touch(a){let b=this.sessions.get(a);b&&(clearTimeout(b.idleTimer),b.idleTimer=this.armIdleTimer(a))}armIdleTimer(a){let b=setTimeout(()=>{this.closeSession(a)},g.MCP_IDLE_MS);return b.unref?.(),b}async closeSession(a){let b=this.sessions.get(a);b&&(this.sessions.delete(a),clearTimeout(b.idleTimer),await b.client.close().catch(()=>{}))}}({load:a=>(0,j.findServer)(a),saveOAuth:(a,b)=>(0,j.saveOAuthData)(a,b),saveConnectionResult:(a,b)=>null===b.lastError?(0,j.syncServerTools)(a,b.toolInfo):(0,j.saveConnectionError)(a,b.lastError),findByOAuthState:a=>(0,j.findServerByOAuthState)(a)},d);let p=o.__thursdayMcpManager;a.s(["McpAuthRequiredError",0,m,"mcpManager",0,p]),c()}catch(a){c(a)}},!1),947950,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(351674),f=a.i(203469),g=a.i(184838),h=a.i(714428),i=a.i(899284),j=b([g]);async function k(a){var b;let[c]=await g.database.select({name:h.mcpServerTable.name,config:h.mcpServerTable.config,lastError:h.mcpServerTable.lastError,toolsSyncedAt:h.mcpServerTable.toolsSyncedAt}).from(h.mcpServerTable).where((0,d.eq)(h.mcpServerTable.name,a));return c?{...c,config:(b=c.config,(0,i.isRemoteConfig)(b)?{url:b.url}:{command:b.command,args:b.args}),tools:await l(a)}:null}async function l(a){return g.database.select({id:h.mcpToolTable.id,name:h.mcpToolTable.name,description:h.mcpToolTable.description,inputSchema:h.mcpToolTable.inputSchema,outputSchema:h.mcpToolTable.outputSchema}).from(h.mcpToolTable).where((0,d.eq)(h.mcpToolTable.serverName,a)).orderBy(h.mcpToolTable.name)}async function m(a){let[b]=await g.database.select().from(h.mcpServerTable).where((0,d.eq)(h.mcpServerTable.name,a));return b??null}[g]=j.then?(await j)():j;let u=()=>f.appEvents.emit({type:"mcp"});async function n(a){let[b]=await g.database.insert(h.mcpServerTable).values({...a,lastError:null}).onConflictDoUpdate({target:h.mcpServerTable.name,set:{config:a.config,lastError:null}}).returning();return u(),b}async function o(a,b){await g.database.transaction(async c=>{b.length&&await c.insert(h.mcpToolTable).values(b.map(b=>({...b,serverName:a}))).onConflictDoUpdate({target:[h.mcpToolTable.serverName,h.mcpToolTable.name],set:{description:p(h.mcpToolTable.description),inputSchema:p(h.mcpToolTable.inputSchema),outputSchema:p(h.mcpToolTable.outputSchema)}}),await c.delete(h.mcpToolTable).where(b.length?(0,d.and)((0,d.eq)(h.mcpToolTable.serverName,a),(0,d.notInArray)(h.mcpToolTable.name,b.map(a=>a.name))):(0,d.eq)(h.mcpToolTable.serverName,a)),await c.update(h.mcpServerTable).set({lastError:null,toolsSyncedAt:new Date}).where((0,d.eq)(h.mcpServerTable.name,a))}),u()}function p(a){return e.sql.raw(`excluded."${a.name}"`)}async function q(a,b){await g.database.update(h.mcpServerTable).set({lastError:b}).where((0,d.eq)(h.mcpServerTable.name,a)),u()}async function r(a,b){await g.database.update(h.mcpServerTable).set({oauth:b}).where((0,d.eq)(h.mcpServerTable.name,a)),u()}async function s(a){let[b]=await g.database.select().from(h.mcpServerTable).where(e.sql`json_extract(${h.mcpServerTable.oauth}, '$.state') = ${a}`);return b??null}async function t(a){let b=await g.database.delete(h.mcpServerTable).where((0,d.eq)(h.mcpServerTable.name,a)).returning();return b.length>0&&u(),b.length>0}a.s(["deleteServer",0,t,"findPinnedTools",0,function(a){return g.database.select({server:h.mcpToolTable.serverName,name:h.mcpToolTable.name,description:h.mcpToolTable.description,inputSchema:h.mcpToolTable.inputSchema}).from(h.botMcpToolTable).innerJoin(h.mcpToolTable,(0,d.eq)(h.botMcpToolTable.toolId,h.mcpToolTable.id)).where((0,d.eq)(h.botMcpToolTable.botName,a)).orderBy(h.mcpToolTable.serverName,h.mcpToolTable.name)},"findServer",0,m,"findServerByOAuthState",0,s,"findServerDetail",0,k,"findToolSchemas",0,function(a,b){return b.length?g.database.select({name:h.mcpToolTable.name,description:h.mcpToolTable.description,inputSchema:h.mcpToolTable.inputSchema}).from(h.mcpToolTable).where((0,d.and)((0,d.eq)(h.mcpToolTable.serverName,a),(0,d.inArray)(h.mcpToolTable.name,b))).orderBy(h.mcpToolTable.name):Promise.resolve([])},"listServerNames",0,function(){return g.database.select({name:h.mcpServerTable.name}).from(h.mcpServerTable).orderBy(h.mcpServerTable.name)},"listToolNames",0,function(a){let b=g.database.select({server:h.mcpToolTable.serverName,name:h.mcpToolTable.name}).from(h.mcpToolTable);return a?b.where((0,d.eq)(h.mcpToolTable.serverName,a)).orderBy(h.mcpToolTable.name):b.orderBy(h.mcpToolTable.serverName,h.mcpToolTable.name)},"saveConnectionError",0,q,"saveOAuthData",0,r,"syncServerTools",0,o,"upsertServer",0,n]),c()}catch(a){c(a)}},!1),899284,a=>{"use strict";var b=a.i(53112),c=a.i(706210);let d=b.z.object({url:b.z.url(),headers:b.z.record(b.z.string(),b.z.string()).optional()}),e=b.z.object({command:b.z.string().min(1),args:b.z.array(b.z.string()).optional(),env:b.z.record(b.z.string(),b.z.string()).optional()}),f=b.z.union([d,e]),g=b.z.object({name:b.z.string(),description:b.z.string().optional(),inputSchema:b.z.looseObject({}).optional(),outputSchema:b.z.looseObject({}).optional()});b.z.object({clientInformation:b.z.looseObject({}).optional(),tokens:b.z.looseObject({}).optional(),authorizationServer:b.z.looseObject({}).optional(),codeVerifier:b.z.string().optional(),state:b.z.string().optional()});let h=b.z.object({name:b.z.string().min(1).max(40),config:f,toolCount:b.z.number().int(),lastError:b.z.string().nullish()}),i=g.extend({id:b.z.number().int(),description:b.z.string().nullish()});h.omit({toolCount:!0}).extend({tools:i.array().default([]),toolsSyncedAt:c.DateLikeSchema});let j=b.z.object({name:b.z.string().min(1,"Name is required").max(40).regex(/^[a-zA-Z0-9_-]+$/,"Only letters, numbers, - and _ are allowed"),config:f});b.z.union([b.z.object({mcpServers:b.z.record(b.z.string(),f)}),b.z.record(b.z.string(),f)]),a.s(["MCPServerFormSchema",0,j,"isRemoteConfig",0,function(a){return"url"in a}])},986743,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(530385),f=a.i(351674),g=a.i(203469);a.i(569572);var h=a.i(184838),i=a.i(714428),j=a.i(661210),k=b([h]);[h]=k.then?(await k)():k;let B=()=>g.appEvents.emit({type:"memory"});async function l(a,b,c={}){let[d]=await h.database.insert(i.memoryNoteTable).values({path:a,description:b,ownedByUser:c.ownedByUser??!1}).onConflictDoNothing({target:i.memoryNoteTable.path}).returning();return d&&B(),d??null}async function m(a,b){let[c]=await h.database.update(i.memoryNoteTable).set({...b,updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,a)).returning();return c&&B(),c??null}async function n(a){let b=await h.database.delete(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.id,a)).returning({id:i.memoryNoteTable.id});return b.length>0&&B(),b.length>0}async function o(a,b){let[c]=await h.database.insert(i.memoryFactTable).values({noteId:a,text:b,source:"user"}).returning();return await r(a),B(),c}async function p(a,b,c){let e=await h.database.transaction(async e=>{let f=await e.update(i.memoryFactTable).set({isLatest:!1}).where((0,d.and)((0,d.eq)(i.memoryFactTable.id,b),(0,d.eq)(i.memoryFactTable.noteId,a),(0,d.eq)(i.memoryFactTable.isLatest,!0))).returning({id:i.memoryFactTable.id});if(0===f.length)return null;let[g]=await e.insert(i.memoryFactTable).values({noteId:a,text:c,source:"user"}).returning();return await e.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,a)),g});return e&&B(),e}async function q(a,b){let c=await h.database.delete(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.id,b),(0,d.eq)(i.memoryFactTable.noteId,a))).returning({id:i.memoryFactTable.id});return c.length>0&&(await r(a),B()),c.length>0}function r(a){return h.database.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,a))}async function s(){for(let a of j.MEMORY_ALWAYS_LISTED){let b=j.MEMORY_PATHS.find(b=>b.path===a)?.of??a;await h.database.insert(i.memoryNoteTable).values({path:a,description:b}).onConflictDoUpdate({target:i.memoryNoteTable.path,set:{description:b}})}}async function t(a,b={}){let c=[...new Set(a.map(a=>a.trim()).filter(Boolean))];if(!c.length)return{notes:[],missing:[]};let g=await h.database.select({id:i.memoryNoteTable.id,path:i.memoryNoteTable.path,description:i.memoryNoteTable.description}).from(i.memoryNoteTable).where((0,d.inArray)(i.memoryNoteTable.path,c)),j=new Map(g.map(a=>[a.path,a])),k=c.filter(a=>!j.has(a));if(!g.length)return{notes:[],missing:k};let l=g.map(a=>a.id),m=await h.database.select({id:i.memoryFactTable.id,noteId:i.memoryFactTable.noteId,text:i.memoryFactTable.text,source:i.memoryFactTable.source,createdAt:i.memoryFactTable.createdAt,saidAt:i.callTable.startedAt}).from(i.memoryFactTable).leftJoin(i.callTable,(0,d.eq)(i.memoryFactTable.callId,i.callTable.id)).where((0,d.and)((0,d.eq)(i.memoryFactTable.isLatest,!0),(0,d.inArray)(i.memoryFactTable.noteId,l))).orderBy((0,e.asc)(i.memoryFactTable.id));return!1!==b.touch&&await h.database.update(i.memoryNoteTable).set({hits:f.sql`${i.memoryNoteTable.hits} + 1`,lastReadAt:new Date}).where((0,d.inArray)(i.memoryNoteTable.id,l)),{notes:c.flatMap(a=>{let b=j.get(a);return b?[{path:b.path,description:b.description,facts:m.filter(a=>a.noteId===b.id).map(a=>({id:a.id,text:a.text,...a.saidAt?{saidAt:a.saidAt}:{}}))}]:[]}),missing:k}}(0,d.inArray)(i.memoryNoteTable.path,j.MEMORY_ALWAYS_LISTED);let C=a=>a.toLowerCase().replace(/[\s.,!?…·'"`]/g,"");async function u(a,b,c,e,f){let g=await a.select({id:i.memoryFactTable.id,text:i.memoryFactTable.text}).from(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.noteId,b),(0,d.eq)(i.memoryFactTable.isLatest,!0))),h=new Map(g.map(a=>[C(a.text),a]));for(let g of c){let c=g.text.trim();if(!c)continue;if(null!=g.replaces){let[j]=await a.select({id:i.memoryFactTable.id,text:i.memoryFactTable.text}).from(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.id,g.replaces),(0,d.eq)(i.memoryFactTable.noteId,b),(0,d.eq)(i.memoryFactTable.isLatest,!0)));if(j){if(C(j.text)===C(c))continue;await a.update(i.memoryFactTable).set({isLatest:!1}).where((0,d.eq)(i.memoryFactTable.id,j.id)),h.delete(C(j.text));let[g]=await a.insert(i.memoryFactTable).values({noteId:b,text:c,source:e,callId:f}).returning({id:i.memoryFactTable.id});h.set(C(c),{...g,text:c});continue}}if(h.has(C(c)))continue;let[j]=await a.insert(i.memoryFactTable).values({noteId:b,text:c,source:e,callId:f}).returning({id:i.memoryFactTable.id});h.set(C(c),{...j,text:c})}await a.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,b))}async function v(a,b,c,e=null){let f=a.trim();if(!await h.database.transaction(async a=>{let[g]=await a.select({id:i.memoryNoteTable.id}).from(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.path,f));return!!g&&(await u(a,g.id,b,c,e),!0)}))return null;let{notes:g}=await t([f],{touch:!1});return B(),g[0]??null}async function w(a,b,c,d,e=null){let f=a.trim();if(!await h.database.transaction(async a=>{let[g]=await a.insert(i.memoryNoteTable).values({path:f,description:b}).onConflictDoNothing({target:i.memoryNoteTable.path}).returning({id:i.memoryNoteTable.id});return!!g&&(await u(a,g.id,c,d,e),!0)}))return null;let{notes:g}=await t([f],{touch:!1});return B(),g[0]??null}async function x(a,b){let[c]=await h.database.update(i.memoryNoteTable).set({description:b,updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.path,a.trim())).returning({id:i.memoryNoteTable.id});return c&&B(),!!c}async function y(){let[a,b]=await Promise.all([h.database.select({id:i.memoryNoteTable.id,path:i.memoryNoteTable.path,description:i.memoryNoteTable.description,hits:i.memoryNoteTable.hits,lastReadAt:i.memoryNoteTable.lastReadAt,createdAt:i.memoryNoteTable.createdAt}).from(i.memoryNoteTable),h.database.select({noteId:i.memoryFactTable.noteId,count:f.sql`count(*)`}).from(i.memoryFactTable).where((0,d.eq)(i.memoryFactTable.isLatest,!0)).groupBy(i.memoryFactTable.noteId)]),c=new Map(b.map(a=>[a.noteId,a.count]));return a.filter(a=>(0,j.isAlwaysListed)(a.path)||(c.get(a.id)??0)>0).sort((a,b)=>Number((0,j.isAlwaysListed)(b.path))-Number((0,j.isAlwaysListed)(a.path))||(0,j.recallScore)(b)-(0,j.recallScore)(a)).map(a=>({path:a.path,description:a.description,factCount:c.get(a.id)??0,lastSeenAt:a.lastReadAt??a.createdAt}))}async function z(a){let b=await h.database.transaction(async b=>{let c=await b.delete(i.memoryFactTable).where((0,d.eq)(i.memoryFactTable.id,a)).returning({noteId:i.memoryFactTable.noteId});if(0===c.length)return null;let e=c[0].noteId,[g]=await b.select({path:i.memoryNoteTable.path,ownedByUser:i.memoryNoteTable.ownedByUser}).from(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.id,e)),[h]=await b.select({count:f.sql`count(*)`}).from(i.memoryFactTable).where((0,d.and)((0,d.eq)(i.memoryFactTable.noteId,e),(0,d.eq)(i.memoryFactTable.isLatest,!0)));return h?.count!==0||!g||g.ownedByUser||(0,j.isAlwaysListed)(g.path)?(await b.update(i.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(i.memoryNoteTable.id,e)),{path:g?.path??"",noteGone:!1}):(await b.delete(i.memoryNoteTable).where((0,d.eq)(i.memoryNoteTable.id,e)),{path:g.path,noteGone:!0})});return b&&B(),b}async function A(){let a=await h.database.delete(i.memoryNoteTable).returning({id:i.memoryNoteTable.id});return await s(),a.length>0&&B(),a.length}a.s(["addFact",0,o,"createNote",0,l,"createNoteWithFacts",0,w,"deleteAllNotes",0,A,"deleteNote",0,n,"describeNote",0,x,"forgetFact",0,q,"forgetFactById",0,z,"listNoteIndex",0,y,"readNotes",0,t,"reviseFact",0,p,"updateNote",0,m,"writeFacts",0,v]),c()}catch(a){c(a)}},!1),661210,a=>{"use strict";var b=a.i(53112),c=a.i(569572),d=a.i(706210);let e=b.z.enum(["user","call","bot"]),f=b.z.string().trim().min(1,"A note needs a line saying what it is about").max(c.MEMORY_LIMITS.descriptionChars,`A note's line is one line: at most ${c.MEMORY_LIMITS.descriptionChars} characters`),g=b.z.object({id:b.z.number(),text:b.z.string(),source:e.nullish(),createdAt:d.DateLikeSchema});b.z.object({id:b.z.number(),path:b.z.string(),description:b.z.string(),ownedByUser:b.z.boolean(),hits:b.z.number(),lastReadAt:d.DateLikeSchema.nullable(),createdAt:d.DateLikeSchema,updatedAt:d.DateLikeSchema,factCount:b.z.number(),facts:g.array()});let h=[{path:"profile",of:"The user themselves — name, age, what they do, where they live, whatever else says who they are"},{path:"preferences",of:"How they want things done, and said — read whole on every call, so a rule for a particular situation goes here too"},{path:"people/",of:"Someone in their life, and what matters about them"},{path:"projects/",of:"Something with an end — a trip, a purchase, a deadline, a thing being built"},{path:"topics/",of:"Something ongoing that keeps coming back"}],i=h.filter(a=>!a.path.endsWith("/")).map(a=>a.path),j=h.filter(a=>a.path.endsWith("/")).map(a=>a.path.slice(0,-1)),k=RegExp(`^(?:${i.join("|")}|(?:${j.join("|")})/.+)$`);a.s(["MEMORY_ALWAYS_LISTED",0,i,"MEMORY_PATHS",0,h,"NoteLineSchema",0,f,"isAlwaysListed",0,a=>i.includes(a),"isMemoryPath",0,a=>k.test(a),"recallScore",0,function(a){let b=(0,d.toDate)(a.lastReadAt??a.createdAt),c=Math.max(0,(Date.now()-b.getTime())/864e5);return(a.hits+1)/(1+c)}])},780946,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(258261),f=a.i(530385),g=a.i(203469),h=a.i(569572),i=a.i(184838),j=a.i(714428),k=a.i(221214),l=a.i(293480),m=a.i(643020),n=b([i,k]);[i,k]=n.then?(await n)():n;let z=()=>g.appEvents.emit({type:"routines"});async function o(a,b){return i.database.select({id:j.threadTable.id,status:j.threadTable.status,outcome:j.threadTable.outcome,updatedAt:j.threadTable.updatedAt}).from(j.threadTable).where((0,d.eq)(j.threadTable.routineId,a)).orderBy((0,f.desc)(j.threadTable.createdAt)).limit(b)}let A=async a=>{let{createdAt:b,...c}=a;return{...c,runs:await o(a.id,h.ROUTINE.runsShown)}};async function p(){let a=await i.database.select().from(j.routineTable).orderBy(j.routineTable.createdAt);return Promise.all(a.map(A))}async function q(a){let[b]=await i.database.select().from(j.routineTable).where((0,d.eq)(j.routineTable.id,a));return b?A(b):null}async function r(a){let b=await q(a.trim());if(b)return b;let c=a.trim().toLowerCase(),d=(await p()).filter(a=>a.label.toLowerCase()===c);return 1===d.length?d[0]:null}async function s(a){let b=await (0,k.findJobBot)(a);return(!b||b.disabled)&&(0,l.publicError)("Choose an enabled bot."),b.name}function t(a,b){b&&"once"===a.kind&&(0,m.momentOf)(a.at)<=new Date&&(0,l.publicError)("That time has passed. Pick a later one.")}async function u(a){let[{total:b}]=await i.database.select({total:(0,e.count)()}).from(j.routineTable);b>=h.ROUTINE.max&&(0,l.publicError)(`There are already ${h.ROUTINE.max} routines. Delete one to make another.`),t(a.schedule,!0);let[c]=await i.database.insert(j.routineTable).values({id:crypto.randomUUID(),...a,bot:await s(a.bot),nextRunAt:(0,m.nextRun)(a.schedule,new Date)}).returning();return z(),A(c)}async function v(a,b){let[c]=await i.database.select().from(j.routineTable).where((0,d.eq)(j.routineTable.id,a));if(!c)return null;let e=b.schedule??c.schedule,f=!!(b.schedule&&!(0,m.sameSchedule)(b.schedule,c.schedule))||b.enabled&&!c.enabled;f&&t(e,b.enabled??c.enabled);let[g]=await i.database.update(j.routineTable).set({...b,...b.bot?{bot:await s(b.bot)}:{},...f?{nextRunAt:(0,m.nextRun)(e,new Date)}:{}}).where((0,d.eq)(j.routineTable.id,a)).returning();return z(),A(g)}async function w(a){let b=await i.database.delete(j.routineTable).where((0,d.eq)(j.routineTable.id,a)).returning({id:j.routineTable.id});return b.length&&z(),b.length>0}async function x(a){return(await o(a,1))[0]??null}async function y(a){return(await i.database.select({id:j.threadTable.id}).from(j.threadTable).where((0,d.and)((0,d.eq)(j.threadTable.routineId,a),(0,d.eq)(j.threadTable.seen,!1),(0,d.inArray)(j.threadTable.status,["done","cancelled"])))).map(a=>a.id)}a.s(["createRoutine",0,u,"deleteRoutine",0,w,"findRoutine",0,q,"latestRun",0,x,"listRoutines",0,p,"listUnseenRunIds",0,y,"resolveRoutine",0,r,"updateRoutine",0,v]),c()}catch(a){c(a)}},!1),643020,a=>{"use strict";var b=a.i(723885),c=a.i(569572),d=a.i(706210);let e=b.default.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"A time is HH:MM, 00:00 to 23:59");function f(a){let[b,c]=a.split(" "),[d,e,f]=b.split("-").map(Number),[g,h]=c.split(":").map(Number);return new Date(d,e-1,f,g,h)}let g=/^\d{4}-\d\d-\d\d ([01]\d|2[0-3]):[0-5]\d$/,h=b.default.string().regex(g,'A moment is "YYYY-MM-DD HH:MM"').refine(a=>{if(!g.test(a))return!0;let b=f(a);return b.getMonth()===Number(a.slice(5,7))-1&&b.getDate()===Number(a.slice(8,10))},"There is no such day"),i=b.default.discriminatedUnion("kind",[b.default.object({kind:b.default.literal("once"),at:h}),b.default.object({kind:b.default.literal("daily"),time:e,days:b.default.array(b.default.number().int().min(1).max(7)).min(1,"Pick at least one day").transform(a=>[...new Set(a)].sort((a,b)=>a-b))}),b.default.object({kind:b.default.literal("every"),hours:b.default.number().int().min(c.ROUTINE.minHours,`No more often than every ${c.ROUTINE.minHours}h`).max(168)})]),j=b.default.object({bot:b.default.string().trim().min(1,"Pick a bot"),label:b.default.string().trim().min(1,"Give it a name").max(80),request:b.default.string().trim().min(1,"Say what it should do"),schedule:i}),k=b.default.object({id:b.default.string(),status:b.default.enum(["running","waiting","done","cancelled"]),outcome:b.default.string().nullable(),updatedAt:d.DateLikeSchema});j.extend({id:b.default.string(),enabled:b.default.boolean(),nextRunAt:d.DateLikeSchema,runs:b.default.array(k)});let l=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],m=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];a.s(["RoutineInputSchema",0,j,"RoutineScheduleSchema",0,i,"momentOf",0,f,"nextRun",0,function(a,b){if("once"===a.kind)return f(a.at);if("every"===a.kind)return new Date(b.getTime()+36e5*a.hours);let[c,d]=a.time.split(":").map(Number);for(let e=0;e<=7;e++){let f=new Date(b);f.setDate(f.getDate()+e),f.setHours(c,d,0,0);let g=0===f.getDay()?7:f.getDay();if(f>b&&a.days.includes(g))return f}return new Date(b.getTime()+864e5)},"sameSchedule",0,function(a,b){if("once"===a.kind)return"once"===b.kind&&a.at===b.at;if("every"===a.kind)return"every"===b.kind&&a.hours===b.hours;let c=a=>[...a].sort((a,b)=>a-b).join();return"daily"===b.kind&&a.time===b.time&&c(a.days)===c(b.days)},"scheduleText",0,function(a){if("once"===a.kind){let[b,c]=a.at.split(" "),[,d,e]=b.split("-").map(Number);return`Once \xb7 ${m[d-1]} ${e} ${c}`}if("every"===a.kind)return 1===a.hours?"Every hour":`Every ${a.hours} hours`;let{days:b,time:c}=a;if(7===b.length)return`Daily ${c}`;if(1===b.length)return`${l[b[0]-1]} ${c}`;let d=b.every((a,c)=>0===c||a===b[c-1]+1)?`${l[b[0]-1]}–${l[b.at(-1)-1]}`:b.map(a=>l[a-1]).join(" ");return`Daily ${c} \xb7 ${d}`}])},487591,422807,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(203469),e=a.i(569572),f=a.i(821415);a.i(176668);let g=a=>a.trim().toLowerCase().replace(/^[a-z]+:\/\//,"").replace(/^www\./,"").replace(/[/?#].*$/,"");a.s(["siteOf",0,g],422807);let h=(0,c.join)(e.DATA_DIR,e.PATHS.signIns),i=a=>(0,c.join)(h,`${encodeURIComponent(g(a))}.json`),j=()=>d.appEvents.emit({type:"signins"});async function k(a){try{return JSON.parse(await (0,b.readFile)(i(a),"utf8"))}catch{return null}}async function l(a){let b=g(a),c=await k(b);if(c)return c;let d=(await n()).map(a=>a.site).filter(a=>b.endsWith(`.${a}`)).sort((a,b)=>b.length-a.length)[0];return d?k(d):null}async function m(a){await (0,b.mkdir)(h,{recursive:!0}),await (0,b.writeFile)(i(a.site),JSON.stringify(a),{mode:384}),j()}async function n(){let a=await (0,b.readdir)(h).catch(()=>[]);return(await Promise.all(a.filter(a=>a.endsWith(".json")).map(a=>k(decodeURIComponent(a.slice(0,-5)))))).flatMap(a=>a?[(({state:a,...b})=>b)(a)]:[]).sort((a,b)=>a.site.localeCompare(b.site))}async function o(a){let b=await l(a.site);if(b&&!b.bots.includes(a.bot)){let c=b.asking.includes(a.bot)?b:{...b,asking:[...b.asking,a.bot]};return c!==b&&await m(c),{kind:"taken",signIn:(({state:a,...b})=>b)(c)}}let c=b?.site??g(a.site),d={site:c,account:a.account.trim()||c,bots:[...new Set([...b?.bots??[],a.bot])],asking:(b?.asking??[]).filter(b=>b!==a.bot),keptAt:new Date().toISOString(),usedAt:b?.usedAt??null,state:a.state};return await m(d),{kind:"kept",signIn:(({state:a,...b})=>b)(d)}}let p=globalThis.__signInsHeld??=new Map;async function q(a,b){let c=await l(a);if(!c)return{kind:"none",kept:(await n()).map(a=>a.site)};if(!c.bots.includes(b))return c.asking.includes(b)||await m({...c,asking:[...c.asking,b]}),{kind:"ask",signIn:(({state:a,...b})=>b)(c)};let d={...c,usedAt:new Date().toISOString()};return await m(d),{kind:"state",signIn:(({state:a,...b})=>b)(d),state:c.state}}async function r(a,b){return(await (0,f.listBrowsers)(a,b)).find(a=>a.name===b.PLAYWRIGHT_CLI_SESSION)??null}async function s(a,b){let c=await r(a,b);return c?c.attached?"theirs":"own":null}async function t(a,b){let c=await r(a,b);return!!c&&!c.attached&&!0===c.headed}let u=a=>`${a.name}
|
|
128
132
|
${a.domain}
|
|
129
133
|
${a.path}`;async function v(a){let b,c=(0,f.jobShellEnv)(a),d=c.PLAYWRIGHT_CLI_SESSION??a,g=p.get(d);if(!g?.sites.size)return;let h=await (0,f.openWorkspace)();if(await s(h,c)!=="own")return void p.delete(d);let i=(0,f.browserStateFile)();try{let a=await h.exec((0,f.saveBrowserState)(i),{env:c,timeoutMs:e.BROWSER_CLI.loadMs});if(0!==a.exitCode)return;let d=JSON.parse(await h.readFile(i,"utf-8"));b=new Map((d.cookies??[]).map(a=>[u(a),a]))}finally{await h.exec(`rm -f ${i}`)}for(let a of g.sites){let c=await k(a),d=c?.state;if(!c||!d?.cookies||!c.bots.includes(g.bot))continue;let e=!1,f=d.cookies.map(a=>{let c=b.get(u(a));return c&&JSON.stringify(c)!==JSON.stringify(a)?(e=!0,c):a});e&&await m({...c,state:{...d,cookies:f}})}}async function w(a,b,c){let d=await k(a);d&&await m({...d,bots:c?[...new Set([...d.bots,b])]:d.bots.filter(a=>a!==b),asking:d.asking.filter(a=>a!==b)})}async function x(a){await (0,b.rm)(i(a),{force:!0}),j()}a.s(["borrowSignIn",0,q,"holdSignIn",0,function(a,b,c){let d=p.get(a);d&&d.bot===b?d.sites.add(c):p.set(a,{bot:b,sites:new Set([c])})},"keepSignIn",0,o,"removeSignIn",0,x,"renewSignIns",0,v,"sessionBrowser",0,s,"sessionWindow",0,t,"setSignInBot",0,w],487591)},138100,a=>a.a(async(b,c)=>{try{var d=a.i(666680),e=a.i(750227),f=a.i(569572),g=a.i(821415),h=a.i(176668),i=a.i(182248),j=a.i(762805),k=b([j]);[j]=k.then?(await k)():k;let m=(0,e.join)(f.APP_DIR,f.PATHS.skills.default),n=(0,e.join)(f.APP_DIR,f.PATHS.skills.seeds),o=(0,e.join)(f.DATA_DIR,f.PATHS.skills.custom),p=async(a,b)=>{let c,d=b?(c=b.trim().toLowerCase(),/^[a-z0-9][a-z0-9_-]*$/.test(c)?(0,e.join)(n,c):null):null;return l(a,b?[m,...d?[d]:[],(0,e.join)(g.WORKSPACE,(0,g.botFolder)(b),f.PATHS.skills.own),o]:[m,o],await (0,j.readSkillsOff)(),await (0,j.readRetired)())};async function l(a,b,c=new Set,e=new Map){let f=[],g=new Set;for(let k of b){let b;try{b=await a.readdir(k,{withFileTypes:!0})}catch{continue}for(let l of b){let b,m;if(!l.isDirectory())continue;let n=`${k}/${l.name}`,o=`${n}/SKILL.md`;try{b=await a.readFile(o,"utf-8")}catch{continue}try{m=(0,j.parseFrontmatter)(b)}catch(a){h.logger.warn(`skill ${n}: SKILL.md front matter did not load — ${(0,i.errorToString)(a)}`);continue}if(!(0,j.runsHere)(m))continue;let p=e.get(m.name);!(p?.has((0,d.createHash)("sha256").update(b,"utf8").digest("hex"))||g.has(m.name))&&(g.add(m.name),(0,j.isSkillOff)(m,c)||f.push({name:m.name,description:m.description,path:n}))}}return f}a.s(["loadSkills",0,p]),c()}catch(a){c(a)}},!1),762805,a=>a.a(async(b,c)=>{try{let C;var d=a.i(666680),e=a.i(912714),f=a.i(750227),g=a.i(622650),h=a.i(569572),i=a.i(221214),j=a.i(725466),k=a.i(951941),l=a.i(821415),m=a.i(176668),n=a.i(293480),o=a.i(182248),p=b([i,j]);function q(a){if("default"===a)return(0,f.resolve)(h.APP_DIR,h.PATHS.skills.default);if("custom"===a)return(0,f.resolve)(h.DATA_DIR,h.PATHS.skills.custom);let b=(0,k.botOfSource)(a)??"";return a.startsWith("kit:")?(0,f.resolve)(h.APP_DIR,h.PATHS.skills.seeds,b.toLowerCase()):(0,f.resolve)(l.WORKSPACE,h.PATHS.bots,b,h.PATHS.skills.own)}function r(a,b){let c=q(a),d=(0,f.resolve)(c,b),e=(0,f.relative)(c,d);return(!e||e.startsWith("..")||e.includes(f.sep)||"."===e)&&(0,n.publicError)("Skill not found"),d}function s(a,b){let c=(0,f.resolve)(a,b),d=(0,f.relative)(a,c);return(d.startsWith("..")||(0,f.isAbsolute)(d))&&(0,n.publicError)("File not found"),c}async function t(a,b){let[c,d]=await Promise.all([(0,e.realpath)(a),(0,e.realpath)(b)]).catch(()=>(0,n.publicError)("File not found")),g=(0,f.relative)(c,d);return(g.startsWith("..")||(0,f.isAbsolute)(g))&&(0,n.publicError)("File not found"),d}function u(a){let b=a.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!b)return{head:null,body:a.trim(),rest:a,fence:""};let c=a.slice(b[0].length);return{head:b[1]??null,body:c.trim(),rest:c,fence:b[0]}}async function v(){try{return(0,k.parseSkillsOff)(await (0,j.readConfig)(k.SKILLS_OFF_KEY))}catch(a){return m.logger.warn(`skills switched off could not be read — ${(0,o.errorToString)(a)}`),new Set}}function w(a){let b,{head:c}=u(a);c||(0,n.publicError)("SKILL.md needs a YAML block with name and description");try{b=(0,g.parse)(c)}catch{(0,n.publicError)("SKILL.md frontmatter is not valid YAML")}let d=k.SkillFrontmatterSchema.safeParse(b);return d.success||(0,n.publicError)(`SKILL.md frontmatter: ${d.error.issues[0]?.message??"invalid"}`),d.data}[i,j]=p.then?(await p)():p;let D=/^disabled[ \t]*:[^\n]*(\r?\n|$)/m;async function x(a,b,c){let d,g=(0,f.join)(r(a,b),"SKILL.md");try{d=await (0,e.readFile)(g,"utf-8")}catch{(0,n.publicError)("Skill not found")}let{name:h}=w(d),i=(0,k.parseSkillsOff)(await (0,j.readConfig)(k.SKILLS_OFF_KEY));if(c?i.add(h.toLowerCase()):i.delete(h.toLowerCase()),await (0,j.writeConfig)(k.SKILLS_OFF_KEY,JSON.stringify([...i].sort())),c||"custom"!==a)return;let{head:l,rest:m,fence:o}=u(d);if(!l||!D.test(l))return;let p=o.includes("\r\n")?"\r\n":"\n",q=l.replace(D,"").replace(/\s+$/,"");await (0,e.writeFile)(g,`---${p}${q}${p}---${p}${m}`)}async function y(a,b,c){try{let g,h=await (0,e.readFile)((0,f.join)(q(a),b,"SKILL.md"),"utf-8"),i=w(h);if(a.startsWith("own:")&&(g=i.name,c.get(g)?.has((0,d.createHash)("sha256").update(h,"utf8").digest("hex"))))return null;return{...i,source:a,dir:b}}catch{return null}}async function z(a,b){let c=r("custom",a),d=async a=>(0,e.stat)(a).then(()=>!0,()=>!1);await d(c)&&(0,n.publicError)(`A skill named "${a}" already exists`),await d(r("default",a))&&(0,n.publicError)(`"${a}" is a built-in skill — pick another name`),await (0,e.mkdir)(c,{recursive:!0});try{for(let[a,d]of b){let b=s(c,a);await (0,e.mkdir)((0,f.resolve)(b,".."),{recursive:!0}),await (0,e.writeFile)(b,d)}}catch(a){throw await (0,e.rm)(c,{recursive:!0,force:!0}),a}let g=await y("custom",a,new Map);return g||(await (0,e.rm)(c,{recursive:!0,force:!0}),(0,n.publicError)("SKILL.md could not be read back")),g}async function A(a,b,c,d){(0,k.isEditableSource)(a)||(0,n.publicError)("A skill that ships with the app is read-only");let f=r(a,b),g=await t(f,s(f,c)),i=await (0,e.stat)(g).catch(()=>null);i?.isFile()||(0,n.publicError)("File not found"),Buffer.byteLength(d)>h.SKILL_FILES.inlineBytes&&(0,n.publicError)("That is larger than this screen can write back"),"SKILL.md"===c&&w(d),await (0,e.writeFile)(g,d,"utf-8")}async function B(a,b){(0,k.isEditableSource)(a)||(0,n.publicError)("A skill that ships with the app can only be switched off");let c=r(a,b);await (0,e.stat)(c).then(()=>!0,()=>!1)||(0,n.publicError)("Skill not found"),await (0,e.rm)(c,{recursive:!0,force:!0})}a.s(["deleteSkill",0,B,"isSkillOff",0,(a,b)=>!0===a.disabled||b.has(a.name.toLowerCase()),"parseFrontmatter",0,w,"readRetired",0,()=>C??=(0,e.readFile)((0,f.join)(h.APP_DIR,h.PATHS.skills.seeds,"retired.json"),"utf8").then(a=>{let{sha256:b}=JSON.parse(a);return new Map(Object.entries(b).map(([a,b])=>[a,new Set(b)]))}).catch(()=>new Map),"readSkillsOff",0,v,"renderSkillMarkdown",0,function(a,b){return`---
|
|
130
134
|
${(0,g.stringify)(a).trim()}
|