thursday-agent 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/build-manifest.json +3 -3
- package/.next/prerender-manifest.json +3 -3
- package/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +2 -2
- package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/api/artifact/route.js +4 -4
- package/.next/server/app/api/artifact/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/memory/files/route.js +3 -3
- package/.next/server/app/api/bot/memory/files/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/memory/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/task/[id]/route.js +8 -8
- package/.next/server/app/api/bot/task/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/task/route.js +6 -6
- package/.next/server/app/api/bot/task/route.js.nft.json +1 -1
- package/.next/server/app/api/config/route.js.nft.json +1 -1
- package/.next/server/app/api/events/route.js.nft.json +1 -1
- package/.next/server/app/api/file/[...path]/route.js +4 -4
- package/.next/server/app/api/file/[...path]/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/catalog/route.js +2 -2
- package/.next/server/app/api/llm-model/catalog/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/credits/route.js +2 -2
- package/.next/server/app/api/llm-model/credits/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/route.js +2 -2
- package/.next/server/app/api/llm-model/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/subscription/route.js +2 -2
- 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 +11 -11
- 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/skills/[source]/[name]/route.js.nft.json +1 -1
- package/.next/server/app/api/skills/route.js.nft.json +1 -1
- 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/skills/route.js +6 -6
- package/.next/server/app/api/thursday/skills/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/tool-call/route.js +8 -8
- package/.next/server/app/api/thursday/tool-call/route.js.nft.json +1 -1
- package/.next/server/app/api/workspace/route.js +3 -2
- package/.next/server/app/api/workspace/route.js.nft.json +1 -1
- package/.next/server/app/artifact/[...path]/page/server-reference-manifest.json +1 -1
- package/.next/server/app/artifact/[...path]/page.js +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/page/server-reference-manifest.json +40 -40
- package/.next/server/app/page.js +3 -3
- package/.next/server/app/page.js.nft.json +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__026u77e._.js +5 -0
- package/.next/server/chunks/[root-of-the-server]__02va5wz._.js +1 -1
- package/.next/server/chunks/{[root-of-the-server]__02xjoto._.js → [root-of-the-server]__050zri4._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__0bg9710._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0in-d5s._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0ncs9uu._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0pa9k-f._.js +8 -0
- package/.next/server/chunks/[root-of-the-server]__0qi_m0e._.js +8 -0
- package/.next/server/chunks/[root-of-the-server]__0tq0m_k._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0xep6j_._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1-ga0kh._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__144l7qt._.js +8 -0
- package/.next/server/chunks/[root-of-the-server]__1_04mcf._.js +2 -2
- package/.next/server/chunks/[root-of-the-server]__1anc1p9._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1jg8t86._.js +8 -0
- package/.next/server/chunks/{[root-of-the-server]__12cabg9._.js → [root-of-the-server]__1lldzy9._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__1orn-5b._.js +4 -3
- package/.next/server/chunks/{[root-of-the-server]__01dkp4a._.js → [root-of-the-server]__1peqvsi._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__1w8gm5h._.js +10 -0
- package/.next/server/chunks/[root-of-the-server]__1xt39nn._.js +8 -0
- package/.next/server/chunks/[root-of-the-server]__1zb8mfo._.js +8 -0
- package/.next/server/chunks/_0-fjql4._.js +11 -6
- package/.next/server/chunks/_00xh_q0._.js +4 -6
- package/.next/server/chunks/_05h2cii._.js +1 -1
- package/.next/server/chunks/{_1_9mjx-._.js → _091bi8d._.js} +1 -1
- package/.next/server/chunks/_0fzqt2y._.js +57 -45
- package/.next/server/chunks/{_0u4aiy2._.js → _0lr92vd._.js} +1 -1
- package/.next/server/chunks/_0mecv0f._.js +11 -6
- package/.next/server/chunks/_0mh8j4m._.js +1 -1
- package/.next/server/chunks/{_0sbynis._.js → _0si7xzn._.js} +1 -1
- package/.next/server/chunks/_0wp4le3._.js +1 -1
- package/.next/server/chunks/_0y5fg-x._.js +1 -1
- package/.next/server/chunks/_1230wbx._.js +5 -5
- package/.next/server/chunks/_15hq89o._.js +1 -1
- package/.next/server/chunks/{_0obojvv._.js → _18d7-5p._.js} +1 -1
- package/.next/server/chunks/{_03kp0jp._.js → _1c78vw5._.js} +71 -61
- package/.next/server/chunks/_1d0j961._.js +2 -2
- package/.next/server/chunks/_1j8k_j5._.js +1 -1
- package/.next/server/chunks/_1krd9rf._.js +1 -1
- package/.next/server/chunks/_1php4eq._.js +1 -1
- package/.next/server/chunks/{_03a0897._.js → _1zkfbaa._.js} +1 -1
- package/.next/server/chunks/config_ts_1g4sz5o._.js +1 -1
- package/.next/server/chunks/features_1qf3cei._.js +6 -1
- package/.next/server/chunks/features_memory_1uqvksn._.js +2 -2
- package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_0r28-sm._.js → node_modules_consola_dist_chunks_prompt_mjs_17k8irj._.js} +1 -1
- package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_1xoq2rl._.js → node_modules_consola_dist_chunks_prompt_mjs_1jidylq._.js} +1 -1
- package/.next/server/chunks/ssr/[root-of-the-server]__0-nob52._.js +4 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__092knlj._.js +3 -0
- package/.next/server/chunks/ssr/{[root-of-the-server]__0_69wqr._.js → [root-of-the-server]__0s4wb56._.js} +1 -1
- package/.next/server/chunks/ssr/{[root-of-the-server]__1eh7hid._.js → [root-of-the-server]__0s9dq5u._.js} +1 -1
- package/.next/server/chunks/ssr/{[root-of-the-server]__0zkv7z_._.js → [root-of-the-server]__0sd3izg._.js} +2 -2
- package/.next/server/chunks/ssr/{[root-of-the-server]__1gtlw6v._.js → [root-of-the-server]__1-13tcn._.js} +3 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__10-dz5o._.js +13 -9
- package/.next/server/chunks/ssr/[root-of-the-server]__1mzi-ju._.js +1 -1
- package/.next/server/chunks/ssr/{[root-of-the-server]__1cyjywu._.js → [root-of-the-server]__1zidpfl._.js} +1 -1
- package/.next/server/chunks/ssr/_001_ms1._.js +6 -1
- package/.next/server/chunks/ssr/{_07uchnc._.js → _04z2c7b._.js} +2 -2
- package/.next/server/chunks/ssr/{_0kbkmar._.js → _06tssji._.js} +2 -2
- package/.next/server/chunks/ssr/_0fk4c7d._.js +3 -0
- package/.next/server/chunks/ssr/_0i_6q1w._.js +2 -2
- package/.next/server/chunks/ssr/{_1xvgn77._.js → _0m2lsd1._.js} +2 -2
- package/.next/server/chunks/ssr/_0mggveb._.js +3 -0
- package/.next/server/chunks/ssr/_0nbpc_8._.js +3 -0
- package/.next/server/chunks/ssr/{_0y0tiht._.js → _0rzucul._.js} +3 -3
- package/.next/server/chunks/ssr/{_0mb8zc8._.js → _0s99bgb._.js} +2 -2
- package/.next/server/chunks/ssr/_0zcjrbg._.js +3 -0
- package/.next/server/chunks/ssr/_1-teee5._.js +4 -4
- package/.next/server/chunks/ssr/{_0c-ql2m._.js → _11j92tu._.js} +2 -2
- package/.next/server/chunks/ssr/_13fke0x._.js +1 -1
- package/.next/server/chunks/ssr/{_01_6m32._.js → _1ebxla1._.js} +2 -2
- package/.next/server/chunks/ssr/_1jdgjv9._.js +3 -0
- package/.next/server/chunks/ssr/{_0u2jv_x._.js → _1lz_cq2._.js} +60 -50
- package/.next/server/chunks/ssr/{_20kd_n0._.js → _1nj4niv._.js} +3 -3
- package/.next/server/chunks/ssr/_1ovmc9s._.js +3 -0
- package/.next/server/chunks/ssr/_1sji22n._.js +1 -1
- package/.next/server/chunks/ssr/_1vyd1ji._.js +1 -1
- package/.next/server/chunks/ssr/features_config_components_config-setting_tsx_0xfwqdg._.js +1 -1
- package/.next/server/chunks/ssr/features_connectors_components_mcp-setting_tsx_0jmbgvp._.js +1 -1
- package/.next/server/chunks/ssr/{node_modules_1-hc6uv._.js → node_modules_0-dr_o7._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_124bue5._.js → node_modules_04sksn9._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1uuj9x1._.js → node_modules_05-n6dz._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1i7u1ia._.js → node_modules_056qgf-._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0lm7_vm._.js → node_modules_07dsgkx._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1h4a4pp._.js → node_modules_0bvopy2._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1bc7gu8._.js → node_modules_0fkeku3._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0h50b8n._.js → node_modules_0ifp389._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0zp9r92._.js → node_modules_0iur59s._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_063xwpp._.js → node_modules_0m383r2._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1bgb6-f._.js → node_modules_0u9da1h._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0bvraul._.js → node_modules_0zeg3x_._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1t9cyee._.js → node_modules_1-y7nni._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1_n3ztw._.js → node_modules_16mkxuo._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0eu1va6._.js → node_modules_1a0kmjl._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0z5tsu8._.js → node_modules_1chvq5f._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0h7u60n._.js → node_modules_1j8j4pt._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0rjg6t1._.js → node_modules_1k6n600._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1xx28h1._.js → node_modules_1k7z2j6._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0h5hnr1._.js → node_modules_1k8j8n0._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0mwym0g._.js → node_modules_1lz0oxc._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1vqb6po._.js → node_modules_1t77e4n._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1l0qtdu._.js → node_modules_1uyk91w._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0y_cded._.js → node_modules_1x0ztf4._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_113tz0l._.js → node_modules_1y79i83._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1juq3hs._.js → node_modules_20c28js._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0d3skpl._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0bkwd0u._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0i44kk5._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0p9a9su._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@vercel_oidc_dist_0qe30a_._.js → node_modules_@vercel_oidc_dist_1o553h-._.js} +1 -1
- package/.next/server/middleware-build-manifest.js +3 -3
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.js +1 -1
- package/.next/server/server-reference-manifest.json +41 -41
- package/.next/static/chunks/{17donp69y4do7.js → 0n3jle9kbqfr2.js} +8 -8
- package/.next/static/chunks/{3ok9_x74rip3v.js → 11r2yp_yh9_qn.js} +1 -1
- package/.next/static/chunks/{26-pr2c9ro222.js → 126fj4pga_72k.js} +1 -1
- package/.next/static/chunks/{2a0k6jlq0_v1u.js → 159udiexf6dom.js} +2 -2
- package/.next/static/chunks/18gi7o2ibrgh8.js +3 -0
- package/.next/static/chunks/{0x79tx04dxbpp.js → 1q9z1tohil7xn.js} +1 -1
- package/.next/static/chunks/{3cfi_q6d_wtci.js → 1sjgfets224re.js} +1 -1
- package/.next/static/chunks/{3agpgkwaa321p.js → 1wszsr83t01gh.js} +1 -1
- package/.next/static/chunks/22_zkas21rpna.js +1 -0
- package/.next/static/chunks/{1ekc7ul556kbl.js → 2szintyibu0s5.js} +1 -1
- package/.next/static/chunks/{1okqiww3pnwka.js → 3-b6b7entqazs.js} +1 -1
- package/.next/static/chunks/3cq5g494yuke8.css +1 -0
- package/.next/static/chunks/{2fzs9fm8yarvq.js → 3dmbhsv2u_8kj.js} +1 -1
- package/.next/static/chunks/{1grhjo7a5a0_-.js → 3i0a5px-oufgc.js} +1 -1
- package/.next/static/chunks/{280t0_e99i276.js → 3wexk9qo8zuj3.js} +3 -3
- package/.next/static/chunks/3xre8bu_pk1p_.js +1 -0
- package/.next/static/chunks/3zv6t3i77xhr_.js +1 -0
- package/.next/static/chunks/{28cizcdaabd4h.js → 408ueu4hfvcg7.js} +1 -1
- package/.next/static/chunks/{3xpbkl66ssib5.js → 435atsnhs7ksu.js} +8 -8
- package/README.md +46 -23
- package/app/api/events/app-event.ts +0 -2
- package/bin/port.mjs +65 -0
- package/bin/thursday.mjs +2 -33
- package/docs/how-it-works.md +11 -7
- package/docs/images/face-dark.png +0 -0
- package/docs/images/face-light.png +0 -0
- package/docs/images/keeps-going.png +0 -0
- package/features/ai/chatgpt.ts +42 -20
- package/features/ai/load-tools.ts +20 -14
- package/features/ai/prompts/bot.prompt.ts +91 -89
- package/features/ai/prompts/thursday.prompt.ts +48 -41
- package/features/ai/tools/bot.tool.ts +3 -3
- package/features/ai/tools/memory.tool.ts +65 -62
- package/features/ai/tools/skills.tool.ts +25 -8
- package/features/ai/tools/tool-name.ts +0 -1
- package/features/ai/tools/workspace.tool.ts +3 -0
- package/features/bot/bot.action.ts +6 -1
- package/features/bot/bot.run.ts +195 -80
- package/features/bot/bot.runner.ts +82 -39
- package/features/bot/bot.schema.ts +25 -0
- package/features/bot/components/bot-room.tsx +57 -4
- package/features/bot/components/bot-tool.tsx +0 -1
- package/features/bot/task.query.ts +132 -10
- package/features/bot/task.store.ts +26 -9
- package/features/memory/components/memory-edit.tsx +7 -5
- package/features/thursday/components/thursday.tsx +0 -3
- package/features/thursday/tool-line.ts +0 -1
- package/features/thursday/use-thursday.ts +1 -1
- package/features/workspace/workspace.ts +27 -20
- package/package.json +1 -1
- package/skills/browser/SKILL.md +6 -5
- package/.next/server/chunks/[root-of-the-server]__04q--0f._.js +0 -8
- package/.next/server/chunks/[root-of-the-server]__0bl-e63._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0jq4ohy._.js +0 -8
- package/.next/server/chunks/[root-of-the-server]__0ls6_8y._.js +0 -8
- package/.next/server/chunks/[root-of-the-server]__1339jnv._.js +0 -8
- package/.next/server/chunks/[root-of-the-server]__18_teo8._.js +0 -8
- package/.next/server/chunks/[root-of-the-server]__1ccon1w._.js +0 -10
- package/.next/server/chunks/[root-of-the-server]__1wa1k7r._.js +0 -8
- package/.next/server/chunks/_1zjrdag._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1ox7hbk._.js +0 -4
- package/.next/server/chunks/ssr/[root-of-the-server]__1pduf5n._.js +0 -3
- package/.next/server/chunks/ssr/_0mo2w06._.js +0 -3
- package/.next/server/chunks/ssr/_13z3f85._.js +0 -3
- package/.next/server/chunks/ssr/_14_lw10._.js +0 -3
- package/.next/server/chunks/ssr/_1eoqg_g._.js +0 -3
- package/.next/server/chunks/ssr/_1spzm8z._.js +0 -3
- package/.next/server/chunks/ssr/lib_date-like_ts_02is0pw._.js +0 -3
- package/.next/static/chunks/0tmgrnlje14-s.js +0 -3
- package/.next/static/chunks/0xzgvc0fkdb6t.js +0 -1
- package/.next/static/chunks/14hgtsjg-kael.css +0 -1
- package/.next/static/chunks/2hw2f6zmt7fmt.js +0 -1
- package/.next/static/chunks/3111pj5wnjgos.js +0 -1
- package/features/memory/components/memory-view.tsx +0 -84
- /package/.next/static/{x1cCqY0kWpR_VcYx_lWO5 → G6-gNoyGDEcgAsq-L4PE1}/_buildManifest.js +0 -0
- /package/.next/static/{x1cCqY0kWpR_VcYx_lWO5 → G6-gNoyGDEcgAsq-L4PE1}/_clientMiddlewareManifest.js +0 -0
- /package/.next/static/{x1cCqY0kWpR_VcYx_lWO5 → G6-gNoyGDEcgAsq-L4PE1}/_ssgManifest.js +0 -0
|
@@ -1,92 +1,94 @@
|
|
|
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(203469),k=a.i(569572),l=a.i(725466),m=a.i(176668),n=a.i(523095),o=a.i(293480),p=a.i(8412),q=a.i(182248),r=a.i(689656),s=b([l]);[l]=s.then?(await s)():s;let C="app_EMoamEEZ73f0CkXaXp7hrann",D="http://localhost:1455/auth/callback",E="thursday",{apiKeyName:F,label:G}=r.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,p.createKeyedLock)();async function t(){u();let a=(0,d.randomBytes)(32).toString("base64url"),b=(0,d.randomBytes)(16).toString("hex"),c=(0,e.createServer)((d,e)=>{v(d.url??"/",{state:b,verifier:a}).then(a=>{e.writeHead(a.status,{"content-type":"text/html; charset=utf-8"}),e.end((0,n.oauthPage)(a.title,a.detail,{autoClose:200===a.status}),()=>{a.last&&J.__chatgptListener===c&&u()})})});await new Promise((a,b)=>{c.once("error",b),c.listen(1455,"127.0.0.1",()=>a())}).catch(a=>{(0,o.publicError)("EADDRINUSE"===a.code?"Port 1455 is in use — another ChatGPT or Codex sign-in is waiting. Finish or close it, then try again.":`Could not wait for the sign-in: ${(0,q.errorToString)(a)}`)}),J.__chatgptListener=c,setTimeout(()=>{J.__chatgptListener===c&&u()},k.CHATGPT_SIGN_IN.waitMs).unref();let f=new URL("https://auth.openai.com/oauth/authorize");return f.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:E}).toString(),f.toString()}function u(){let a=J.__chatgptListener;J.__chatgptListener=null,a?.close(),a?.closeIdleConnections()}async function v(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 Config.",last:!1};try{let a=await w({grant_type:"authorization_code",code:e,code_verifier:b.verifier,redirect_uri:D});return await (0,l.writeConfig)(F,JSON.stringify(a)),j.appEvents.emit({type:"config"}),{status:200,title:"Signed in to ChatGPT",detail:"Bots can run on your plan now. This window closes itself.",last:!0}}catch(a){return m.logger.warn({cause:a},"chatgpt sign-in failed"),{status:502,title:"Sign-in failed",detail:(0,q.errorToString)(a),last:!0}}}async function w(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=>{m.logger.warn({cause:a},"chatgpt token endpoint unreachable"),(0,o.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,o.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,o.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 x(){let a=await (0,l.readConfig)(F);if(!a)return null;try{return I.parse(JSON.parse(a))}catch{return null}}let L=a=>a.expires-k.CHATGPT_SIGN_IN.renewBeforeMs<=Date.now();async function y(){let a=await x();return(a||(0,o.publicError)(H),L(a))?K(F,async()=>{let a=await x();if(a||(0,o.publicError)(H),!L(a))return a;try{let b=await w({grant_type:"refresh_token",refresh_token:a.refresh});return await (0,l.writeConfig)(F,JSON.stringify(b)),b}catch(a){(0,o.publicError)(`Could not renew the ${G} sign-in (${(0,q.errorToString)(a)}). If it keeps failing, sign in again from Config.`)}}):a}async function z(a,b){let c=await y(),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?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:`${G} 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}}})}})},"startChatGptSignIn",0,t]),c()}catch(a){c(a)}},!1),738131,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(868468),f=a.i(569572),g=a.i(938934),h=a.i(978876),i=a.i(375827),j=a.i(138902),k=a.i(345846),l=a.i(622547),m=a.i(451017),n=a.i(762008),o=a.i(547613),p=a.i(446957),q=a.i(986743),r=a.i(138100),s=a.i(569549),t=a.i(821415),u=a.i(706210),v=a.i(176668),w=a.i(987674),x=a.i(182248),y=b([j,k,l,q,s]);async function z(b){let{listTaskHistory:c}=await a.A(242808),d=await c({limit:5});if(!d.length)return"No jobs have been handed over yet.";let e=d.map(a=>`"${a.label}" (${a.bot}, ${a.status})`).join(", ");return`There is no job called "${b}". The latest are: ${e}. Call again with one of those names.`}async function A(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,w.estimateTokens)(f)+(0,w.estimateTokens)(JSON.stringify(b))})}c.sort((a,b)=>b.tokens-a.tokens);let e=c.reduce((a,b)=>a+b.tokens,0);v.logger.debug(`${a} tools ${e} tokens over ${c.length} — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`)}async function B(a){let b=await C(a);return f.IS_DEV&&await A(a.target,b),b}async function C(b){if("memory-edit"===b.target){let a=(0,k.createMemoryTools)("user",null,{countReads:!1});return{[n.TOOL_NAMES.memory_recall]:a[n.TOOL_NAMES.memory_recall],[n.TOOL_NAMES.memory_remember]:a[n.TOOL_NAMES.memory_remember],[n.TOOL_NAMES.memory_forget]:a[n.TOOL_NAMES.memory_forget]}}let c=(0,k.createMemoryTools)("call","thursday"===b.target?b.callId??null:null),f=await (0,t.openWorkspace)();if("thursday"===b.target){var v;let{[n.TOOL_NAMES.memory_show]:j,...k}=c,{crowded:l,heavy:t}=(0,g.tidying)(await (0,q.listNoteIndex)()),w=await (0,s.readCallSkillsOn)()?(0,m.createSkillTools)({sandbox:f,skills:await (0,r.loadSkills)(f)}):{};return{...k,...l||t.length?{[n.TOOL_NAMES.memory_show]:j}:{},...w,...(0,o.createWorkspaceTools)(f,{write:!1}),...(v=b.callId,{[n.TOOL_NAMES.delegate]:(0,d.tool)({description:h.delegateSpec.description,inputSchema:h.delegateSpec.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 handed over — call again with one of those.`}let{startTask:h}=await a.A(763543);return{taskId:await h({bot:g.name,request:c,label:d,callId:v}),note:`${g.name} has "${d}". Say so and keep talking — the result is put in front of you later. Everything further about it — an answer, a correction, carrying it on after it answers — is \`${n.TOOL_NAMES.task}\` with "${d}".`}}}),[n.TOOL_NAMES.task]:(0,d.tool)({description:h.taskSpec.description,inputSchema:h.taskSpec.parameters,execute:async({action:b,task:c,answer:d})=>{let{listTaskHistory:f,resolveTask:h}=await a.A(242808);if("status"===b){let a=d?.trim()?{note:"The text in `answer` was not passed on — `status` only reads. Send it again as `answer` if the bot is meant to hear it."}:{},b={now:(0,g.clockNow)()};if(c){let d=await h(c);return d?{...b,...a,label:d.label,bot:d.bot,status:d.status,since:(0,e.formatDistanceToNowStrict)((0,u.toDate)(d.updatedAt),{addSuffix:!0}),outcome:d.outcome,..."waiting"===d.status&&d.pending?.options.length?{options:d.pending.options}:{}}:await z(c)}let i=await f({limit:8});return{...b,...a,tasks:i.map(a=>({label:a.label,bot:a.bot,status:a.status,since:(0,e.formatDistanceToNowStrict)((0,u.toDate)(a.updatedAt),{addSuffix:!0}),...a.ask?{asking:a.ask.question,options:a.ask.options}:{},..."running"===a.status?{now:(0,p.taskActivity)(a.lines)}:{},...a.outcome&&"waiting"!==a.status?{outcome:(0,x.clip)(a.outcome,200)}:{}}))}}let{listInboxTasks:i}=await a.A(242808),j=c?await h(c):"answer"===b?(await i())[0]??null:null;if(!j)return c?await z(c):"answer"===b?"No job has moved yet — say which one, or check `status` first.":"Say which job — by its label. Call `status` with no job named to see them.";let{answerTask:k,cancelTask:l}=await a.A(763543);return"cancel"===b?(await l(j.id),{label:j.label,status:"cancelled"}):d?.trim()?(await k(j.id,d.trim()),{label:j.label,bot:j.bot,status:"running",note:"running"===j.status?"The bot reads it before its next step.":"The bot picks the job back up from there."}):"Say what to pass on."}})}),...i.CALL_TOOLS}}let w=await (0,r.loadSkills)(f);return{[n.TOOL_NAMES.memory_recall]:c[n.TOOL_NAMES.memory_recall],[n.TOOL_NAMES.memory_conversation]:c[n.TOOL_NAMES.memory_conversation],...await (0,l.createSearchTool)(b.model,f),...(0,o.createWorkspaceTools)(f,{write:!0,env:(0,t.jobShellEnv)(b.session),guide:!0}),...await (0,j.createMcpTools)(b.bot,f),...(0,m.createSkillTools)({sandbox:f,skills:w}),[n.TOOL_NAMES.ask_thursday]:h.askThursdayTool,[n.TOOL_NAMES.answer]:h.answerTool}}[j,k,l,q,s]=y.then?(await y)():y,a.s(["loadTools",0,B]),c()}catch(a){c(a)}},!1),875931,a=>a.a(async(b,c)=>{try{var d=a.i(938537),e=a.i(140358),f=a.i(345364),g=a.i(655819),h=a.i(652685),i=a.i(438766),j=a.i(47919);a.i(569572);var k=a.i(688034),l=a.i(725466),m=a.i(176668),n=a.i(293480),o=a.i(182248),p=a.i(652619),q=a.i(689656),r=b([l,p]);[l,p]=r.then?(await r)():r;let A=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENOTFOUND","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","UND_ERR_SOCKET","UND_ERR_CLOSED","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),B=/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,C=null;function s(a){if(null==a||""===a)return null;let b=Number(a);return Number.isFinite(b)?Math.round(1e6*b*1e4)/1e4:null}async function t(){if(C&&Date.now()-C.at<6e5)return C.models;let a=await fetch("https://ai-gateway.vercel.sh/v1/models",{headers:{accept:"application/json"}}).catch(a=>{m.logger.warn({cause:a},"gateway catalog unreachable"),(0,n.publicError)("Could not reach the gateway")});a.ok||(0,n.publicError)(`The gateway answered ${a.status}`);let b=((await a.json()).data??[]).filter(a=>!!a.id).map(a=>{let b;return{id:a.id,label:a.name||a.id,owner:a.owned_by||a.id.slice(0,a.id.indexOf("/")),type:(b=a.type??null)===q.GATEWAY_TEXT&&(a.modalities?.output??[]).includes("image")?"image":b,tags:a.tags??[],price:function(a){let b=a.pricing??{},c=s(b.input),d=s(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)return{in:null,out:null,note:`$${f.cost_per_second}/s ${f.resolution}`,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}}).sort((a,b)=>a.id.localeCompare(b.id));return C={at:Date.now(),models:b},b}async function u(a,b){if(b&&b>0)return b;let c="vercel-ai-gateway"===a.provider?await t().catch(()=>[]):[];return(0,q.compactAtFor)((0,q.contextWindowOf)(a.provider,a.model,c))}async function v(){return await t().then(a=>new Set(a.map(a=>a.id))).catch(()=>null)}async function w(a,b){if("vercel-ai-gateway"!==a)return b;let c=await v();if(!c)return b;let d=b.filter(a=>c.has(a.id));return d.length>0?d:b}async function x(a){let{label:b,apiKeyName:c,signIn:h}=q.TEXT_MODEL_PROVIDERS[a.provider],j=await (0,l.readConfig)(c);return j||(0,n.publicError)(h?`${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,f.createOpenAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"chatgpt":return{ref:a,model:(0,p.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,e.createGoogleGenerativeAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.googleSearch({})}}}case"xai":{let c=(0,g.createXai)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"vercel-ai-gateway":{let c=(0,i.createGateway)({apiKey:b});return{ref:a,model:c(a.model),searchTools:null}}default:(0,n.publicError)(`Not supported provider: ${String(a.provider)}`)}}(a,j)}async function y(a){let b=async a=>(0,q.defaultModelOf)({suggestModels:await w(a.id,a.suggestModels)}),c=a?q.TEXT_MODEL_PROVIDER_LIST.find(b=>b.id===a):void 0,d=q.SPEACH_MODEL_PROVIDER_LIST.map(a=>({...q.TEXT_MODEL_PROVIDERS[a.id],id:a.id}));if(c){let a=await b(c);if(a)return{provider:c.id,model:a}}let e=(0,q.parseTextModel)(await (0,l.readConfig)(k.DEFAULT_MODEL_KEY)??void 0);if(e&&await (0,l.readConfig)(q.TEXT_MODEL_PROVIDERS[e.provider].apiKeyName))return e;for(let a of[...d,...q.TEXT_MODEL_PROVIDER_LIST]){if(!await (0,l.readConfig)(a.apiKeyName))continue;let c=await b(a);if(c)return m.logger.info(`no model set, falling back to ${a.id}/${c}`),{provider:a.id,model:c}}(0,n.publicError)("No model key is set — add one in Config")}async function z(a){let b=(0,q.parseMediaModel)(await (0,l.readConfig)(k.MEDIA_MODEL_KEYS[a]));if(!b||!(0,q.canMakeKind)(b.provider,a))return null;let c=await (0,l.readConfig)(q.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,f.createOpenAI)({apiKey:b}).image(a.model);case"google":return(0,e.createGoogleGenerativeAI)({apiKey:b}).image(a.model);case"xai":return(0,g.createXai)({apiKey:b}).image(a.model);case"vercel-ai-gateway":return(0,i.createGateway)({apiKey:b}).image(a.model);default:(0,n.publicError)(`Not supported image provider: ${String(a.provider)}`)}},"buildSpeechModel",0,function(a,b){switch(a.provider){case"openai":return(0,f.createOpenAI)({apiKey:b}).speech(a.model);case"google":return(0,e.createGoogleGenerativeAI)({apiKey:b}).speech(a.model);case"xai":return(0,g.createXai)({apiKey:b}).speech();case"vercel-ai-gateway":return(0,i.createGateway)({apiKey:b}).speech(a.model);default:(0,n.publicError)(`Not supported speech provider: ${String(a.provider)}`)}},"buildTranscriptionModel",0,function(a,b){switch(a.provider){case"openai":return(0,f.createOpenAI)({apiKey:b}).transcription(a.model);case"google":return(0,e.createGoogleGenerativeAI)({apiKey:b}).transcription(a.model);case"xai":return(0,g.createXai)({apiKey:b}).transcription();case"vercel-ai-gateway":return(0,i.createGateway)({apiKey:b}).transcription(a.model);default:(0,n.publicError)(`Not supported transcription provider: ${String(a.provider)}`)}},"buildVideoModel",0,function(a,b){switch(a.provider){case"google":return(0,e.createGoogleGenerativeAI)({apiKey:b}).video(a.model);case"xai":return(0,g.createXai)({apiKey:b}).video(a.model);case"vercel-ai-gateway":return(0,i.createGateway)({apiKey:b}).video(a.model);default:(0,n.publicError)(`${a.provider} has no video model`)}},"compactBudget",0,u,"getTextModel",0,x,"modelErrorToString",0,function(a){if(!h.APICallError.isInstance(a))return(0,o.errorToString)(a);let b=a.statusCode?` (${a.statusCode})`:"",c=a.responseBody?.trim(),d=c&&!c.includes(a.message)?` ${(0,o.clip)(c,300)}`:"";return`${a.message}${b}${d}`},"modelFailureOf",0,function(a){let b=!1;for(let c of function(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),j.RetryError.isInstance(a)&&c.push(...a.errors),"cause"in a&&c.push(a.cause))}return b}(a)){let{statusCode:a,isRetryable:d,code:e,name:f,message:g}=c,i=h.APICallError.isInstance(c)?c.responseBody??"":"";if((void 0===a||400===a||413===a)&&B.test(`${String(g??"")} ${i}`))return"overflow";(!0===d||"TimeoutError"===f||j.NoOutputGeneratedError.isInstance(c)||"number"==typeof a&&(408===a||409===a||429===a||a>=500)||"string"==typeof e&&A.has(e))&&(b=!0)}return b?"transient":"fatal"},"resolveDefaultModel",0,y,"resolveMediaRef",0,z]),c()}catch(a){c(a)}},!1),735502,a=>a.a(async(b,c)=>{try{var d=a.i(569572),e=a.i(762008),f=a.i(641301),g=a.i(221214),h=a.i(947950),i=a.i(986743),j=a.i(138100),k=a.i(821415),l=a.i(176668),m=a.i(182248),n=a.i(644468),o=a.i(938934),p=b([g,h,i,n]);async function q(a,b,c,p){var q,r,A,B,C,D,E,F,G;let H,I,J,K,L,M=await (0,k.openWorkspace)(),N=a.trim(),O=c?.askedBy??null,[P,Q,R,S,T,U,V,W,X]=await Promise.all([(0,j.loadSkills)(M),(0,i.listNoteIndex)(),(0,i.listAlwaysLoaded)(),(0,n.listConnectedToolNames)(),(0,h.findPinnedTools)(N),(0,g.listJobBots)(),(0,f.listBotMemory)(N),(0,g.readBotMemoryOn)(),(0,k.readMachineTools)(M)]),Y=c&&!c.canBorrow?[]:U.filter(a=>a.name!==N&&!c?.above.includes(a.name)),Z=[O?(q=N,r=O,[`You are ${q}, a worker. ${r} has handed you one part of a job Thursday handed over; your first message says who holds it and how it reached you. The user speaks to Thursday and to nobody else; you never address them, and what you hand back goes into ${r}'s answer as-is. This thread is drawn on their screen while you work: not written to them, but not private either. ${(0,o.nowLine)()}`,s,t].join("\n\n")):(A=N,[`You are ${A}, a worker. Thursday handed you a job while she keeps talking to the user — they speak to her and to nobody else, and what she says out of your answer is the only part of this that reaches them. You are not in that conversation and never address the user. This thread is drawn on their screen while you work, though: not written to them, but not private either. ${(0,o.nowLine)()}`,s,t].join("\n\n")),(B=Q,C=R,H=`## The user's memory
|
|
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(203469),k=a.i(569572),l=a.i(725466),m=a.i(176668),n=a.i(523095),o=a.i(293480),p=a.i(8412),q=a.i(182248),r=a.i(689656),s=b([l]);[l]=s.then?(await s)():s;let C="app_EMoamEEZ73f0CkXaXp7hrann",D="http://localhost:1455/auth/callback",E=["127.0.0.1","::1"],F="thursday",{apiKeyName:G,label:H}=r.TEXT_MODEL_PROVIDERS.chatgpt,I=`${H} is not signed in — sign in from Config.`,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,p.createKeyedLock)();async function t(){u();let a=(0,d.randomBytes)(32).toString("base64url"),b=(0,d.randomBytes)(16).toString("hex"),c=[],f=(d,e)=>{v(d.url??"/",{state:b,verifier:a}).then(a=>{e.writeHead(a.status,{"content-type":"text/html; charset=utf-8"}),e.end((0,n.oauthPage)(a.title,a.detail,{autoClose:200===a.status}),()=>{a.last&&K.__chatgptListeners===c&&u()})})};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,o.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,q.errorToString)(d)}`)}}K.__chatgptListeners=c,setTimeout(()=>{K.__chatgptListeners===c&&u()},k.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 u(){let a=K.__chatgptListeners;for(let b of(K.__chatgptListeners=null,a??[]))b.close(),b.closeIdleConnections()}async function v(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 Config.",last:!1};try{let a=await w({grant_type:"authorization_code",code:e,code_verifier:b.verifier,redirect_uri:D});return await (0,l.writeConfig)(G,JSON.stringify(a)),j.appEvents.emit({type:"config"}),{status:200,title:"Signed in to ChatGPT",detail:"Bots can run on your plan now. This window closes itself.",last:!0}}catch(a){return m.logger.warn({cause:a},"chatgpt sign-in failed"),{status:502,title:"Sign-in failed",detail:(0,q.errorToString)(a),last:!0}}}async function w(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=>{m.logger.warn({cause:a},"chatgpt token endpoint unreachable"),(0,o.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,o.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,o.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 x(){let a=await (0,l.readConfig)(G);if(!a)return null;try{return J.parse(JSON.parse(a))}catch{return null}}let M=a=>a.expires-k.CHATGPT_SIGN_IN.renewBeforeMs<=Date.now();async function y(){let a=await x();return(a||(0,o.publicError)(I),M(a))?L(G,async()=>{let a=await x();if(a||(0,o.publicError)(I),!M(a))return a;try{let b=await w({grant_type:"refresh_token",refresh_token:a.refresh});return await (0,l.writeConfig)(G,JSON.stringify(b)),b}catch(a){(0,o.publicError)(`Could not renew the ${H} sign-in (${(0,q.errorToString)(a)}). If it keeps failing, sign in again from Config.`)}}):a}async function z(a,b){let c=await y(),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}}})}})},"startChatGptSignIn",0,t]),c()}catch(a){c(a)}},!1),738131,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(868468),f=a.i(569572),g=a.i(938934),h=a.i(978876),i=a.i(375827),j=a.i(138902),k=a.i(345846),l=a.i(622547),m=a.i(451017),n=a.i(762008),o=a.i(547613),p=a.i(446957),q=a.i(138100),r=a.i(569549),s=a.i(821415),t=a.i(706210),u=a.i(176668),v=a.i(987674),w=a.i(182248),x=b([j,k,l,r]);async function y(b){let{listTaskHistory:c}=await a.A(242808),d=await c({limit:5});if(!d.length)return"No jobs have been handed over yet.";let e=d.map(a=>`"${a.label}" (${a.bot}, ${a.status})`).join(", ");return`There is no job called "${b}". The latest are: ${e}. Call again with one of those names.`}async function z(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,v.estimateTokens)(f)+(0,v.estimateTokens)(JSON.stringify(b))})}c.sort((a,b)=>b.tokens-a.tokens);let e=c.reduce((a,b)=>a+b.tokens,0);u.logger.debug(`${a} tools ${e} tokens over ${c.length} — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`)}async function A(a){let b=await B(a);return f.IS_DEV&&await z(a.target,b),b}async function B(b){if("memory-edit"===b.target){let a=(0,k.createMemoryTools)("user",null,{countReads:!1});return{[n.TOOL_NAMES.memory_recall]:a[n.TOOL_NAMES.memory_recall],[n.TOOL_NAMES.memory_remember]:a[n.TOOL_NAMES.memory_remember],[n.TOOL_NAMES.memory_forget]:a[n.TOOL_NAMES.memory_forget]}}let c=(0,k.createMemoryTools)("call","thursday"===b.target?b.callId??null:null),u=await (0,s.openWorkspace)();if("thursday"===b.target){var v;let j=await (0,r.readCallSkillsOn)()?(0,m.createSkillTools)({sandbox:u,skills:await (0,q.loadSkills)(u)}):{};return{...c,...j,...(0,o.createWorkspaceTools)(u,{write:!1,timeoutMs:f.CALL_EXEC_TIMEOUT_MS}),...(v=b.callId,{[n.TOOL_NAMES.delegate]:(0,d.tool)({description:h.delegateSpec.description,inputSchema:h.delegateSpec.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 handed over — call again with one of those.`}let{startTask:h}=await a.A(763543);return{taskId:await h({bot:g.name,request:c,label:d,callId:v,from:"thursday"}),note:`${g.name} has "${d}". Say so and keep talking — the result is put in front of you later. Everything further about it — an answer, a correction, carrying it on after it answers — is \`${n.TOOL_NAMES.task}\` with "${d}".`}}}),[n.TOOL_NAMES.task]:(0,d.tool)({description:h.taskSpec.description,inputSchema:h.taskSpec.parameters,execute:async({action:b,task:c,answer:d})=>{let{listTaskHistory:f,resolveTask:h}=await a.A(242808);if("status"===b){let a=d?.trim()?{note:"The text in `answer` was not passed on — `status` only reads. Send it again as `answer` if the bot is meant to hear it."}:{},b={now:(0,g.clockNow)()};if(c){let d=await h(c);return d?{...b,...a,label:d.label,bot:d.bot,status:d.status,since:(0,e.formatDistanceToNowStrict)((0,t.toDate)(d.updatedAt),{addSuffix:!0}),outcome:d.outcome,..."waiting"===d.status&&d.pending?.options.length?{options:d.pending.options}:{}}:await y(c)}let i=await f({limit:8});return{...b,...a,tasks:i.map(a=>({label:a.label,bot:a.bot,status:a.status,since:(0,e.formatDistanceToNowStrict)((0,t.toDate)(a.updatedAt),{addSuffix:!0}),...a.ask?{asking:a.ask.question,options:a.ask.options}:{},..."running"===a.status?{now:(0,p.taskActivity)(a.lines)}:{},...a.outcome&&"waiting"!==a.status?{outcome:(0,w.clip)(a.outcome,200)}:{}}))}}let{listInboxTasks:i}=await a.A(242808),j=c?await h(c):"answer"===b?(await i())[0]??null:null;if(!j)return c?await y(c):"answer"===b?"No job has moved yet — say which one, or check `status` first.":"Say which job — by its label. Call `status` with no job named to see them.";let{answerTask:k,cancelTask:l}=await a.A(763543);return"cancel"===b?(await l(j.id),{label:j.label,status:"cancelled"}):d?.trim()?(await k(j.id,d.trim(),"thursday"),{label:j.label,bot:j.bot,status:"running",note:"running"===j.status?"The bot reads it before its next step.":"The bot picks the job back up from there."}):"Say what to pass on."}})}),...i.CALL_TOOLS}}let x=await (0,q.loadSkills)(u);return{[n.TOOL_NAMES.memory_recall]:c[n.TOOL_NAMES.memory_recall],[n.TOOL_NAMES.memory_conversation]:c[n.TOOL_NAMES.memory_conversation],...await (0,l.createSearchTool)(b.model,u),...(0,o.createWorkspaceTools)(u,{write:!0,env:(0,s.jobShellEnv)(b.session),guide:!0}),...await (0,j.createMcpTools)(b.bot,u),...(0,m.createSkillTools)({sandbox:u,skills:x}),[n.TOOL_NAMES.ask_thursday]:h.askThursdayTool,[n.TOOL_NAMES.answer]:h.answerTool}}[j,k,l,r]=x.then?(await x)():x,a.s(["loadTools",0,A]),c()}catch(a){c(a)}},!1),875931,a=>a.a(async(b,c)=>{try{var d=a.i(938537),e=a.i(140358),f=a.i(345364),g=a.i(655819),h=a.i(652685),i=a.i(438766),j=a.i(47919);a.i(569572);var k=a.i(688034),l=a.i(725466),m=a.i(176668),n=a.i(293480),o=a.i(182248),p=a.i(652619),q=a.i(689656),r=b([l,p]);[l,p]=r.then?(await r)():r;let A=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENOTFOUND","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","UND_ERR_SOCKET","UND_ERR_CLOSED","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),B=/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,C=null;function s(a){if(null==a||""===a)return null;let b=Number(a);return Number.isFinite(b)?Math.round(1e6*b*1e4)/1e4:null}async function t(){if(C&&Date.now()-C.at<6e5)return C.models;let a=await fetch("https://ai-gateway.vercel.sh/v1/models",{headers:{accept:"application/json"}}).catch(a=>{m.logger.warn({cause:a},"gateway catalog unreachable"),(0,n.publicError)("Could not reach the gateway")});a.ok||(0,n.publicError)(`The gateway answered ${a.status}`);let b=((await a.json()).data??[]).filter(a=>!!a.id).map(a=>{let b;return{id:a.id,label:a.name||a.id,owner:a.owned_by||a.id.slice(0,a.id.indexOf("/")),type:(b=a.type??null)===q.GATEWAY_TEXT&&(a.modalities?.output??[]).includes("image")?"image":b,tags:a.tags??[],price:function(a){let b=a.pricing??{},c=s(b.input),d=s(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)return{in:null,out:null,note:`$${f.cost_per_second}/s ${f.resolution}`,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}}).sort((a,b)=>a.id.localeCompare(b.id));return C={at:Date.now(),models:b},b}async function u(a,b){if(b&&b>0)return b;let c="vercel-ai-gateway"===a.provider?await t().catch(()=>[]):[];return(0,q.compactAtFor)((0,q.contextWindowOf)(a.provider,a.model,c))}async function v(){return await t().then(a=>new Set(a.map(a=>a.id))).catch(()=>null)}async function w(a,b){if("vercel-ai-gateway"!==a)return b;let c=await v();if(!c)return b;let d=b.filter(a=>c.has(a.id));return d.length>0?d:b}async function x(a){let{label:b,apiKeyName:c,signIn:h}=q.TEXT_MODEL_PROVIDERS[a.provider],j=await (0,l.readConfig)(c);return j||(0,n.publicError)(h?`${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,f.createOpenAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"chatgpt":return{ref:a,model:(0,p.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,e.createGoogleGenerativeAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.googleSearch({})}}}case"xai":{let c=(0,g.createXai)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"vercel-ai-gateway":{let c=(0,i.createGateway)({apiKey:b});return{ref:a,model:c(a.model),searchTools:null}}default:(0,n.publicError)(`Not supported provider: ${String(a.provider)}`)}}(a,j)}async function y(a){let b=async a=>(0,q.defaultModelOf)({suggestModels:await w(a.id,a.suggestModels)}),c=a?q.TEXT_MODEL_PROVIDER_LIST.find(b=>b.id===a):void 0,d=q.SPEACH_MODEL_PROVIDER_LIST.map(a=>({...q.TEXT_MODEL_PROVIDERS[a.id],id:a.id}));if(c){let a=await b(c);if(a)return{provider:c.id,model:a}}let e=(0,q.parseTextModel)(await (0,l.readConfig)(k.DEFAULT_MODEL_KEY)??void 0);if(e&&await (0,l.readConfig)(q.TEXT_MODEL_PROVIDERS[e.provider].apiKeyName))return e;for(let a of[...d,...q.TEXT_MODEL_PROVIDER_LIST]){if(!await (0,l.readConfig)(a.apiKeyName))continue;let c=await b(a);if(c)return m.logger.info(`no model set, falling back to ${a.id}/${c}`),{provider:a.id,model:c}}(0,n.publicError)("No model key is set — add one in Config")}async function z(a){let b=(0,q.parseMediaModel)(await (0,l.readConfig)(k.MEDIA_MODEL_KEYS[a]));if(!b||!(0,q.canMakeKind)(b.provider,a))return null;let c=await (0,l.readConfig)(q.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,f.createOpenAI)({apiKey:b}).image(a.model);case"google":return(0,e.createGoogleGenerativeAI)({apiKey:b}).image(a.model);case"xai":return(0,g.createXai)({apiKey:b}).image(a.model);case"vercel-ai-gateway":return(0,i.createGateway)({apiKey:b}).image(a.model);default:(0,n.publicError)(`Not supported image provider: ${String(a.provider)}`)}},"buildSpeechModel",0,function(a,b){switch(a.provider){case"openai":return(0,f.createOpenAI)({apiKey:b}).speech(a.model);case"google":return(0,e.createGoogleGenerativeAI)({apiKey:b}).speech(a.model);case"xai":return(0,g.createXai)({apiKey:b}).speech();case"vercel-ai-gateway":return(0,i.createGateway)({apiKey:b}).speech(a.model);default:(0,n.publicError)(`Not supported speech provider: ${String(a.provider)}`)}},"buildTranscriptionModel",0,function(a,b){switch(a.provider){case"openai":return(0,f.createOpenAI)({apiKey:b}).transcription(a.model);case"google":return(0,e.createGoogleGenerativeAI)({apiKey:b}).transcription(a.model);case"xai":return(0,g.createXai)({apiKey:b}).transcription();case"vercel-ai-gateway":return(0,i.createGateway)({apiKey:b}).transcription(a.model);default:(0,n.publicError)(`Not supported transcription provider: ${String(a.provider)}`)}},"buildVideoModel",0,function(a,b){switch(a.provider){case"google":return(0,e.createGoogleGenerativeAI)({apiKey:b}).video(a.model);case"xai":return(0,g.createXai)({apiKey:b}).video(a.model);case"vercel-ai-gateway":return(0,i.createGateway)({apiKey:b}).video(a.model);default:(0,n.publicError)(`${a.provider} has no video model`)}},"compactBudget",0,u,"getTextModel",0,x,"modelErrorToString",0,function(a){if(!h.APICallError.isInstance(a))return(0,o.errorToString)(a);let b=a.statusCode?` (${a.statusCode})`:"",c=a.responseBody?.trim(),d=c&&!c.includes(a.message)?` ${(0,o.clip)(c,300)}`:"";return`${a.message}${b}${d}`},"modelFailureOf",0,function(a){let b=!1;for(let c of function(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),j.RetryError.isInstance(a)&&c.push(...a.errors),"cause"in a&&c.push(a.cause))}return b}(a)){let{statusCode:a,isRetryable:d,code:e,name:f,message:g}=c,i=h.APICallError.isInstance(c)?c.responseBody??"":"";if((void 0===a||400===a||413===a)&&B.test(`${String(g??"")} ${i}`))return"overflow";(!0===d||"TimeoutError"===f||j.NoOutputGeneratedError.isInstance(c)||"number"==typeof a&&(408===a||409===a||429===a||a>=500)||"string"==typeof e&&A.has(e))&&(b=!0)}return b?"transient":"fatal"},"resolveDefaultModel",0,y,"resolveMediaRef",0,z]),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(762008),g=a.i(641301),h=a.i(221214),i=a.i(947950),j=a.i(986743),k=a.i(138100),l=a.i(821415),m=a.i(706210),n=a.i(176668),o=a.i(182248),p=a.i(644468),q=a.i(938934),r=b([h,i,j,p]);async function s(a,b,c,r){var s,t,D,E,F,G,H,I;let J,K,L=await (0,l.openWorkspace)(),M=a.trim(),N=c?.askedBy??null,[O,P,Q,R,S,T,U,V]=await Promise.all([(0,k.loadSkills)(L),(0,j.listNoteIndex)(),(0,p.listConnectedToolNames)(),(0,i.findPinnedTools)(M),(0,h.listJobBots)(),(0,g.listBotMemory)(M),(0,h.readBotMemoryOn)(),(0,l.readMachineTools)(L)]),W=c&&!c.canBorrow?[]:S.filter(a=>a.name!==M&&!c?.above.includes(a.name)),X=[N?(s=M,t=N,[`You are ${s}, one of the bots that work for the user. ${(0,q.nowLine)()}
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
${u}
|
|
4
|
+
- **${t}** — a bot on this job, who handed you one part of it. They cannot see your thread.
|
|
5
|
+
- **You** — you do that part. What you hand back goes into ${t}'s work as it is, never to Thursday or the user.`,v,w].join("\n\n")):(D=M,[`You are ${D}, one of the bots that work for the user. ${(0,q.nowLine)()}
|
|
4
6
|
|
|
5
|
-
${
|
|
7
|
+
${u}
|
|
8
|
+
- **You** — you do the work. Your answer goes to Thursday, not to the user, and she tells them what they need from it.`,v,w].join("\n\n")),(E=P,`## Thursday's memory of the user
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
What Thursday keeps from talking with them. Open a note from the listing with \`${f.TOOL_NAMES.memory_recall}\` when the job needs something about them; what you find out about them goes in your answer, and she keeps what matters.
|
|
8
11
|
|
|
9
|
-
|
|
12
|
+
path — what is under it (facts) "what the user calls it"
|
|
10
13
|
|
|
11
|
-
|
|
14
|
+
${(0,q.noteLines)(E)}`),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?" What is not listed above you are already holding — it is in your tools.":"";return`## Connected tools
|
|
12
15
|
|
|
13
|
-
|
|
16
|
+
${(0,q.mcpToolLines)(d)}
|
|
14
17
|
|
|
15
|
-
|
|
18
|
+
Names only: \`${f.TOOL_NAMES.tool_search}\` returns what each one takes, \`${f.TOOL_NAMES.tool_call}\` runs one.${e}`}(Q,R),(F=O,0===F.length?"":`## Skills
|
|
16
19
|
|
|
17
|
-
|
|
20
|
+
Written-down methods. Use the instructions already in your conversation. When the job needs a skill whose full instructions are absent, read it with \`${f.TOOL_NAMES.load_skill}\` before starting.
|
|
18
21
|
|
|
19
|
-
|
|
22
|
+
${(0,q.skillLines)(F)}`),y(L.cwd,V,r),U?(G=(0,g.botMemoryFolder)(M),J=(H=T).entries.length?H.entries.map(({file:a,line:b,at:c})=>{let f=b?` — ${(0,o.clip)(b,e.PROMPT_LINE.botMemory)}`:"";return`- ${a}${f} \xb7 ${(0,d.format)((0,m.toDate)(c),"yyyy-MM-dd")}`}).join("\n"):"Empty.",K=H.total>H.entries.length?`
|
|
20
23
|
|
|
21
|
-
|
|
24
|
+
The newest ${H.entries.length} of ${H.total}; \`ls ${G}\` for the rest.`:"",`## Your memory
|
|
22
25
|
|
|
23
|
-
|
|
26
|
+
What you kept from your own earlier jobs, in \`${G}/\` under the Cwd above: one topic per file, its first line saying what it holds, read by no other bot. Keep what a later job would otherwise have to find out again — how a site signs in, the way through its screens, a command that turned out right — with the date you found it true, and fix or delete a file that proved wrong. No passwords, keys or codes.
|
|
24
27
|
|
|
25
|
-
${
|
|
28
|
+
${J}${K}`):"",(I=W,0===I.length?"":`## Bots
|
|
29
|
+
|
|
30
|
+
${I.map(a=>`- **${a.name}** — ${a.description}`).join("\n")}
|
|
26
31
|
|
|
27
32
|
These lines were written for the user, who reads them on their own screen: where one says "you" it means them, not you.
|
|
28
33
|
|
|
29
|
-
A part of your job another bot is for goes to \`${
|
|
30
|
-
${
|
|
34
|
+
A part of your job another bot is for goes to \`${f.TOOL_NAMES.ask_bot}\`, because their tools and their practice are the reason they exist. What you build is made of what they bring back, so send for it before you build. A part you could finish in a couple of commands is yours; one that would take a run of its own is theirs. What you were handed stays yours and you answer for it. They get the job, the call it came from and what you write them — not this thread.`),N?A(N):z,N?C(N):B,x(b)].filter(Boolean).join("\n\n");return(0,q.logPromptSize)("bot",X),n.logger.debug(`bot prompt
|
|
35
|
+
${X}`),{text:X,peers:W.map(a=>a.name),opening:null}}[h,i,j,p]=r.then?(await r)():r;let u=`- **The user** — the one person all of this is for. They talk with Thursday by voice, and they follow this job on their screen.
|
|
36
|
+
- **Thursday** — their own personal assistant, one to one. She holds the conversation with them, hands bots the work that takes time, and tells them what comes back.`,v=`**You are on a real computer — the user's own.** You have a shell and a filesystem, and the job is done, not described: where there is no tool for something, write one — in \`node\` unless they asked for another language, the runtime this app itself runs on. Reach for \`${f.TOOL_NAMES.bash}\` before concluding that something cannot be done, but after the roster, not instead of it: a script you write to do another bot's job is the long way round.
|
|
31
37
|
|
|
32
38
|
**What is missing gets installed**, onto the machine once they say yes. What is already there is nobody's question — Environment says what this machine has.
|
|
33
39
|
|
|
34
|
-
**Bring back the thing itself** — their own machine, their own accounts, their own copy of whatever they sent you for — not a smaller safer version of it, and not a note on why you did not.`,
|
|
40
|
+
**Bring back the thing itself** — their own machine, their own accounts, their own copy of whatever they sent you for — not a smaller safer version of it, and not a note on why you did not.`,w="**Never present a guess as a result.** She says it out loud as fact. Say which part is unverified and why.",x=a=>a?.trim()?`## Owner's instructions
|
|
35
41
|
|
|
36
42
|
Written by the person this bot works for. Where these and anything above disagree, these win.
|
|
37
43
|
|
|
38
|
-
${a.trim()}`:"",
|
|
44
|
+
${a.trim()}`:"",y=(a,b,c)=>{var d;let g,h;return`## Environment
|
|
39
45
|
|
|
40
46
|
Current Cwd: ${a}
|
|
41
47
|
Platform: ${process.platform}
|
|
42
|
-
${
|
|
48
|
+
${d=b,g=(a,b)=>`${a}: ${b.found.length?b.found.join(", "):"none"}.${b.missing.length?` Not here: ${b.missing.join(", ")}.`:""}`,h=d.managers.found.includes("pnpm")?" Use pnpm, not npm — this workspace is fenced for it (`pnpm-workspace.yaml`, `.npmrc`).":"",[g("Runtimes",d.runtimes),`${g("Package managers",d.managers)}${h}`,null===d.browser?"":d.browser?"Browser: installed.":"Browser: not installed — `playwright-cli install-browser chromium` puts one there."].filter(Boolean).join("\n")}
|
|
43
49
|
|
|
44
50
|
Read off this machine as the job opened, so it is current: reach for what is here instead of checking for it.
|
|
45
51
|
|
|
46
|
-
Your workspace — \`${
|
|
52
|
+
Your workspace — \`${f.TOOL_NAMES.bash}\` runs here. Everything you write goes in one of these, and they are kept apart because what is in them lives for different lengths of time:
|
|
47
53
|
|
|
48
|
-
- \`${
|
|
49
|
-
- \`${
|
|
50
|
-
- \`${c?.scratch??
|
|
51
|
-
- \`${c?.own??
|
|
54
|
+
- \`${e.PATHS.artifacts}/\` — finished work the user opens, one entry per result. Theirs, and it stays.
|
|
55
|
+
- \`${e.PATHS.projects}/\` — code you build, one folder each. It outlives this job, and a project's dependencies install inside it, never at the workspace root.
|
|
56
|
+
- \`${c?.scratch??e.PATHS.scratch}/\` — this job's working material, one folder for every bot on the job: what another bot on it wrote is here too. It is cleared ${Math.round(e.WORKSPACE_KEEP.forMs/864e5)} days after the job ends, so nothing here is worth keeping.
|
|
57
|
+
- \`${c?.own??e.PATHS.bots}/\` — yours, across every job you run here: your memory, a script you wrote once and will want again, a table you built.
|
|
52
58
|
|
|
53
|
-
Never the directory above — that is the app you run in; outside the workspace, only where the user pointed you.`},
|
|
59
|
+
Never the directory above — that is the app you run in; outside the workspace, only where the user pointed you.`},z=`## Asking
|
|
54
60
|
|
|
55
|
-
What you cannot get for yourself — a decision between real options, a detail only the conversation has, a go-ahead before deleting or sending — goes to \`${
|
|
61
|
+
What you cannot get for yourself — a decision between real options, a detail only the conversation has, a go-ahead before deleting or sending — goes to \`${f.TOOL_NAMES.ask_thursday}\`, once, with everything in it. Ask before you start, not after an hour; never ask what one command would tell you.
|
|
56
62
|
|
|
57
63
|
A job that arrives without its shape — several ways to do it, no telling what it is for, a scale nobody named — is planned before it is built: put the plan up in two or three lines with what you need decided. A job asked for as one thing is built, not proposed.
|
|
58
64
|
|
|
59
|
-
Only what is theirs alone stops the job: a password, a one-time code, a passkey, a permission on their machine. Set it up one action away, ask, and carry on when the answer comes back.`,
|
|
65
|
+
Only what is theirs alone stops the job: a password, a one-time code, a passkey, a permission on their machine. Set it up one action away, ask, and carry on when the answer comes back.`,A=a=>`## Asking
|
|
60
66
|
|
|
61
|
-
What you cannot get for yourself goes to \`${
|
|
67
|
+
What you cannot get for yourself goes to \`${f.TOOL_NAMES.ask_back}\`: ${a} handed you this part and answers from what they have. They cannot take a question to the user, so for what is the user's alone take the safer reading and say so in what you hand back. Ask before you start, once, whole.`,B=`## Answering
|
|
62
68
|
|
|
63
|
-
Every job ends with \`${
|
|
69
|
+
Every job ends with \`${f.TOOL_NAMES.answer}\`. **Answer what was asked, at the size it was asked**: a question ends in its answer — one number is one line — and a thing to make comes back made, an action done, photos in a page, a comparison in a table. Once you have what they asked for the job is done; the next thing you would go and check is theirs to ask for.
|
|
64
70
|
|
|
65
|
-
You are answering Thursday, not the user: she
|
|
71
|
+
You are answering Thursday, not the user: she picks what to say out of this. Write it plainly, in the user's language — the thread is on their screen as you write it. Anything past a few lines is a file under \`${e.PATHS.artifacts}/\`, and the answer names its path — it becomes a link on their screen. In a \`.md\`, images only by absolute route (\`/api/file/${e.PATHS.artifacts}/…\`).`,C=a=>`## Answering
|
|
66
72
|
|
|
67
|
-
Every part ends with \`${
|
|
73
|
+
Every part ends with \`${f.TOOL_NAMES.answer}\`; what you hand back goes into ${a}'s own answer. Hand back what the brief asked for, in the shape it asked for, with everything you learned that bears on it — exact values, the paths of files you wrote, what did not work. They cannot see your thread, so long is right here.`;function t(a,b){let c=a.length-1,d=a.map((d,e)=>{if(0===e)return e===c?`- **${d} (you)** — ${"user"===b?"the user handed you this job on their screen, not during a call":"Thursday handed you this job during a call"}.`:`- **${d}** — holds this job and answers for it.`;let f=a[e-1];return e===c?`- **${d} (you)** — ${f} handed you one part of it: the last section below. You answer to ${f}; nobody else hears from you.`:`- **${d}** — ${f} handed them one part of it.`});return`## Who is on this job
|
|
68
74
|
|
|
69
|
-
-
|
|
70
|
-
- **Thursday** — the user's assistant on that call. Hands jobs to bots and tells the user what comes back.
|
|
71
|
-
${c.join("\n")}`}a.s(["OPENING_TURNS",0,10,"buildHandoff",0,function(a){let b=a.bots.at(-1)??"",c=a.bots.at(-2)??"",d=a.did?.trim()?`## ${c} → ${b}: what ${c} has done, and why this part is ${b}'s
|
|
75
|
+
${d.join("\n")}`}a.s(["OPENING_TURNS",0,10,"buildHandoff",0,function(a){let b=a.bots.at(-1)??"",c=a.bots.at(-2)??"",d=a.did?.trim()?`## ${c} → ${b}: what ${c} has done, and why this part is ${b}'s
|
|
72
76
|
|
|
73
77
|
${a.did.trim()}`:"",e=`## ${c} → ${b}: the part
|
|
74
78
|
|
|
75
|
-
${a.part.trim()}`;return[{type:"text",text:
|
|
79
|
+
${a.part.trim()}`;return[{type:"text",text:t(a.bots)},{type:"text",text:[a.chain,d,e].filter(Boolean).join("\n\n")}]},"buildTaskOpening",0,function(a){let b=a.conversation.filter(a=>a.text.trim()),c="user"===a.from?"The user":"Thursday",d=`## ${c} → ${a.bot}: the job
|
|
76
80
|
|
|
77
|
-
${a.request.trim()}`,
|
|
81
|
+
${a.request.trim()}`,f=b.length?`## The call the job came from — its last ${b.length} turns, verbatim
|
|
78
82
|
|
|
79
83
|
A detail missing from the job may be here — a name, a number, which of two. Where the two disagree the job wins, unless they asked out loud for something to be done and the job only asks about it: then the doing is the job.
|
|
80
84
|
|
|
81
|
-
${b.map(a=>`${"user"===a.role?"user":"thursday"}: ${(0,
|
|
85
|
+
${b.map(a=>`${"user"===a.role?"user":"thursday"}: ${(0,o.clip)(a.text,e.PROMPT_LINE.callTurn)}`).join("\n")}`:"";return[{type:"text",text:t([a.bot],a.from)},{type:"text",text:[d,f].filter(Boolean).join("\n\n")}]},"chainOf",0,function(a){return a?.role!=="user"?"":"string"==typeof a.content?a.content:a.content.flatMap(a=>"text"===a.type?[a.text]:[]).at(-1)??""},"loadBotPrompt",0,s]),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);e.TOOL_NAMES.memory_recall,e.TOOL_NAMES.memory_remember,e.TOOL_NAMES.memory_forget,e.TOOL_NAMES.bash,e.TOOL_NAMES.web_search,e.TOOL_NAMES.load_skill,e.TOOL_NAMES.end_call;var f=a.i(706210),g=a.i(176668),h=a.i(987674),i=a.i(182248);let j=(a=new Date)=>`${(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm")} ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,k=a=>`${(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm")} (${(0,c.formatDistanceToNowStrict)(a,{addSuffix:!0})})`;a.s(["callStamp",0,k,"carriedLines",0,a=>a.map(a=>`- ${a.text} \xb7 ${a.path} #${a.id}`).join("\n"),"clockNow",0,j,"conversationLines",0,a=>a.map(a=>"tool"===a.role?`you → ${a.tool??"tool"}`:`${"user"===a.role?"user":"you"}: ${a.text}`).join("\n"),"logPromptSize",0,function(a,b){let c=(0,h.sectionTokens)(b),e=c.reduce((a,b)=>a+b.tokens,0);g.logger.debug(`${a} prompt ${e} tokens — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`);let f=c[0];e>d.PROMPT_BUDGET&&f&&g.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.`)},"mcpServerLines",0,function(a){let b=new Map;for(let c of a)b.set(c.server,(b.get(c.server)??0)+1);return[...b].map(([a,b])=>`- **${a}**: ${b} tool${1===b?"":"s"}`).join("\n")},"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=a.aliases?.length?` ${a.aliases.map(a=>`"${a}"`).join(" ")}`:"",g=b?` \xb7 ${c=a.lastSeenAt,(d=Math.floor((Date.now()-(0,f.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}${g}`}).join("\n"):"(nothing saved yet)"},"nowLine",0,(a=new Date)=>`**Now**: ${j(a)}`,"recentCallLines",0,function(a,b){let c=[],f=0;a:for(let g=a.length-1;g>=0;g--){let j=a[g];for(let a=j.turns.length-1;a>=0;a--){let g=function(a,b){if("tool"!==a.role)return`${"user"===a.role?"user":"you"}: ${a.text}`;let c=`you → ${a.tool??"tool"} ${(0,i.clip)(a.text,d.PROMPT_LINE.toolArgs)}`;if(a.tool!==e.TOOL_NAMES.delegate)return c;let f=function(a,b){if(a!==e.TOOL_NAMES.delegate)return null;try{let a=JSON.parse(b);return"string"==typeof a.label?a.label:null}catch{return null}}(a.tool,a.text),g=f?b.jobs?.find(a=>a.label===f):void 0;if(!g)return c;let h=g.outcome?`: ${(0,i.clip)(g.outcome,d.PROMPT_LINE.jobOutcome)}`:"";return`you → ${a.tool} "${g.label}" (${g.id}) — ${g.status}${h}`}(j.turns[a],j),k=(0,h.estimateTokens)(g)+3;if(f+k>b&&c.length)break a;f+=k,c.push({call:j,line:g})}}c.reverse();let g=[],j=null;for(let{call:a,line:b}of c)a!==j&&(j=a,g.push(`### ${k(a.startedAt)}`)),g.push(b);return g.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,f;return`- **${a.name}**: ${b.short?(c=a.description,e=d.PROMPT_LINE.skill,(f=c.trim().split(/(?<=[.。])\s|\n/)[0].trim()).length>e?`${f.slice(0,e).trim()}…`:f):a.description}`}).join("\n"),"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)})],938934)},375827,a=>{"use strict";var b=a.i(527990),c=a.i(794219),d=a.i(762008);let e={name:d.TOOL_NAMES.end_call,description:`End the call.
|
|
82
86
|
|
|
83
|
-
Say goodbye first — nothing said after this reaches the user.`,parameters:c.object({})},f=(0,b.tool)({description:e.description,inputSchema:e.parameters}),g={[d.TOOL_NAMES.end_call]:f};a.s(["CALL_TOOLS",0,g])},138902,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(762008),g=a.i(947950),h=a.i(644468),i=b([g,h]);[g,h]=i.then?(await i)():i;let l={[f.TOOL_NAMES.tool_search]:{name:f.TOOL_NAMES.tool_search,description:`Return the description and exact inputSchema of tools on a connected server, so they can be called with \`${f.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 8 come back.")})},[f.TOOL_NAMES.tool_call]:{name:f.TOOL_NAMES.tool_call,description:`Run one tool whose definition came back from \`${f.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.record(e.string(),e.unknown()).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.")})}},m=(a,b)=>`${a.replace(/[^a-zA-Z0-9]+/g,"_")}__${b.replace(/[^a-zA-Z0-9_-]+/g,"_")}`.slice(0,64);async function j(a,b){let[c,e]=await Promise.all([(0,h.listConnectedToolNames)(),(0,g.findPinnedTools)(a)]),f={};for(let a of e){let c=m(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,h.callConnectedTool)(b,a.server,a.name,c??void 0,d)}))}return c.length>e.length&&Object.assign(f,n(b)),f}async function k(a){let b=(await (0,h.listConnectedToolNames)(a)).map(a=>a.name);if(b.length)return`Tools on "${a}": ${b.join(", ")}.`;let c=await (0,h.listConnectedServerNames)();return c.length?`There is no server called "${a}". Connected: ${c.join(", ")}.`:"Nothing is connected."}let n=a=>({[f.TOOL_NAMES.tool_search]:(0,d.tool)({description:l[f.TOOL_NAMES.tool_search].description,inputSchema:l[f.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,8),e=await (0,h.findConnectedSchemas)(a.trim(),d);if(!e.length)return{tools:[],note:await k(a)};let f=d.filter(a=>!e.some(b=>b.name===a)),g=c.slice(8),i=[f.length?`Not on "${a}": ${f.join(", ")}.`:"",g.length?`Only 8 at a time — ask again for: ${g.join(", ")}.`:""].filter(Boolean);return{tools:e,...i.length?{note:i.join(" ")}:{}}}}),[f.TOOL_NAMES.tool_call]:(0,d.tool)({description:l[f.TOOL_NAMES.tool_call].description,inputSchema:l[f.TOOL_NAMES.tool_call].parameters,execute:async({server:b,tool:c,args:d},{abortSignal:e})=>(await (0,h.listConnectedToolNames)(b.trim())).some(a=>a.name===c.trim())?(0,h.callConnectedTool)(a,b.trim(),c.trim(),d??void 0,e):{status:"error",text:await k(b)}})});a.s(["createMcpTools",0,j]),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(203469),g=a.i(569572),h=a.i(938934),i=a.i(762008),j=a.i(986743),k=a.i(661210),l=a.i(569549),m=b([j,l]);[j,l]=m.then?(await m)():m;let n="Deleted for good. The listing in your instructions is from when this session opened and still shows it that way until the next one.",o=a=>({...a,facts:a.facts.map(({saidAt:a,...b})=>a?{...b,said:(0,h.saidStamp)(a)}:b),factCount:a.facts.length}),p=a=>"user"===a?"Typed on the screen — there is no conversation behind it.":"bot"===a?"Saved by a bot during a job — there is no conversation behind it.":"The conversation it was saved in is not kept.",q=a=>a>g.MEMORY_LIMITS.factsPerNote?` This note now holds ${a} facts, past the ${g.MEMORY_LIMITS.factsPerNote} one note holds well. Ask the user which of it is no longer true and delete what they name.`:"";a.s(["createMemoryTools",0,(a,b=null,{countReads:c=!0}={})=>({[i.TOOL_NAMES.memory_recall]:(0,d.tool)({description:"Open one note from the listing, whole.",inputSchema:e.object({path:e.string().describe("Exactly as the listing writes it — the path, or one of the names in quotes after it.")}),execute:async({path:a})=>{let{notes:b}=await (0,j.readNotes)([a],{touch:c}),d=b[0];if(!d)return{note:`Nothing on the listing called ${a.trim()}.`};let e=q(d.facts.length);return e?{...o(d),note:e.trim()}:o(d)}}),[i.TOOL_NAMES.memory_remember]:(0,d.tool)({description:"Write to one note: facts, and the line the listing shows for it. The path is the key — a path not on the listing is created (with at least one fact), one that is gets amended.",inputSchema:e.object({path:e.string().describe("Exactly as the listing writes it, or a new path following the same convention."),facts:e.object({text:e.string().describe("One statement that stands on its own later."),replaces:e.number().int().nullish().describe("The id of the fact this replaces — from this note as handed back here or by `memory_recall`. Null if this is new. A fact that stopped being true is replaced rather than deleted, and so is a note saying the same thing twice: replacing keeps what changed on the record, deleting does not."),alwaysLoad:e.boolean().nullish().describe(`True carries this line into every call's instructions without opening its note — for what to call them, their language and register, a standing rule. At most ${g.MEMORY_LIMITS.carried}. Null leaves it; false makes a carried line an ordinary fact.`)}).array().nullish().describe("What to write under this note. Send everything that came up at once: one call is one pause in the conversation, three calls are three. Null when only naming it."),description:e.string().nullish().describe(`One line saying what this note is about, not what it currently says. Give it for a new note, or when the line no longer fits. Null leaves it; ${k.APP_NAMED_NOTES.join(", ")} keep their own line.`),aliases:e.string().array().nullish().describe('What the user calls this note out loud, in the language they say it — the words they would use to ask for it, not the facts inside. A note at people/yuri might be "Yuri" and "my wife". Replaces the set it has, so send the whole set. Null leaves it.')}),execute:async c=>{let d=c.path.trim(),e=await (0,j.resolveNotePath)(d),f=c.aliases??null,h=e??d,i=(0,k.isAppNamed)(h)?(0,k.appNoteLine)(h):c.description?.trim()||null,l=c.facts??[];if(!l.length&&!i&&!f)return{note:"Nothing to write: send facts, a line, names, or any of them."};if(!e&&!l.length)return{note:`Nothing on the listing called ${d}. A note comes into being with a fact — send at least one.`};let m=e||(0,k.isMemoryPath)(d)?{path:h,description:i,aliases:f,facts:l}:{path:k.MEMORY_INBOX,description:(0,k.appNoteLine)(k.MEMORY_INBOX),facts:l},n=await (0,j.writeNotes)([m],a,b),p=m.path!==d?` Filed under ${m.path}: "${d}" is not a path this listing can carry. If that is not where it belongs, write it again under one that is.`:"",r=n.unnamed.length?` ${n.unnamed[0]} is new and has no line yet — the listing shows its first fact instead. Call again with \`description\` (one line about what it is) and \`aliases\` (the names they say for it).`:"",s=n.notLoaded.length?` All ${g.MEMORY_LIMITS.carried} carried lines are taken, so ${n.notLoaded.map(a=>`"${a}"`).join(", ")} saved as an ordinary fact. Say which carried line you would drop for it and let them choose.`:"",t=o(n.notes[0]);return{...t,note:`Saved. The listing in your instructions is from when this session opened and will not show this until the next one — the note below is current.${p}${r}${s}${q(t.factCount)}`}}}),[i.TOOL_NAMES.memory_conversation]:(0,d.tool)({description:"Open the conversation a fact was saved in, whole: what each side said, and which tools were used.",inputSchema:e.object({factId:e.number().int().describe("The id that came with the fact when its note was opened."),page:e.number().int().min(1).nullish().describe(`${g.MEMORY_CONVERSATION_PAGE} turns a page, oldest first. Null for the first.`)}),execute:async({factId:a,page:c})=>{let d=await (0,j.findFactCall)(a);if(!d)return{note:`No fact with id ${a}.`};if(!d.callId)return{note:p(d.source)};if(d.callId===b)return{note:"Said in this call — it is the conversation you are in."};let e=c??1,f=await (0,l.readCallConversation)(d.callId,e,g.MEMORY_CONVERSATION_PAGE);if(!f)return{note:p(d.source)};let i=Math.max(1,Math.ceil(f.total/g.MEMORY_CONVERSATION_PAGE));return e>i?{note:`That conversation has ${i} page${i>1?"s":""}.`}:{when:(0,h.callStamp)(f.startedAt),page:e,pages:i,conversation:(0,h.conversationLines)(f.turns)}}}),[i.TOOL_NAMES.memory_show]:(0,d.tool)({description:`Put a note on the user's screen so they can see it while you
|
|
84
|
-
talk about it, and take it away again. They cannot edit it there — they say
|
|
85
|
-
what to drop and you drop it.`,inputSchema:e.object({path:e.string().nullable().describe("The note to put on screen, exactly as the listing writes it. Null takes it away.")}),execute:async({path:a})=>{if(!a?.trim())return f.appEvents.emit({type:"memory-view",path:null}),{note:"Taken off the screen."};let{notes:b}=await (0,j.readNotes)([a],{touch:!1}),c=b[0];return c?(f.appEvents.emit({type:"memory-view",path:c.path}),{...c,note:"It is on their screen now, in this order. Ask what they no longer need, and forget only what they name."}):{note:`Nothing on the listing called ${a.trim()}.`}}}),[i.TOOL_NAMES.memory_forget]:(0,d.tool)({description:"Delete one fact for good.",inputSchema:e.object({factId:e.number().int().describe("The id that came with the fact when the note was opened.")}),execute:async({factId:a})=>{let b=await (0,j.forgetFactById)(a);if(!b)return{note:`No fact with id ${a}. Nothing was deleted.`};if(b.noteGone)return{note:`${n} That was the last fact under ${b.path}, so the note went with it.`};let{notes:c}=await (0,j.readNotes)([b.path],{touch:!1});return{...c[0],note:n}}})})]),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 o=`Answer the question from the web. Lead with the answer, then
|
|
87
|
+
Say goodbye first — nothing said after this reaches the user.`,parameters:c.object({})},f=(0,b.tool)({description:e.description,inputSchema:e.parameters}),g={[d.TOOL_NAMES.end_call]:f};a.s(["CALL_TOOLS",0,g])},138902,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(762008),g=a.i(947950),h=a.i(644468),i=b([g,h]);[g,h]=i.then?(await i)():i;let l={[f.TOOL_NAMES.tool_search]:{name:f.TOOL_NAMES.tool_search,description:`Return the description and exact inputSchema of tools on a connected server, so they can be called with \`${f.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 8 come back.")})},[f.TOOL_NAMES.tool_call]:{name:f.TOOL_NAMES.tool_call,description:`Run one tool whose definition came back from \`${f.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.record(e.string(),e.unknown()).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.")})}},m=(a,b)=>`${a.replace(/[^a-zA-Z0-9]+/g,"_")}__${b.replace(/[^a-zA-Z0-9_-]+/g,"_")}`.slice(0,64);async function j(a,b){let[c,e]=await Promise.all([(0,h.listConnectedToolNames)(),(0,g.findPinnedTools)(a)]),f={};for(let a of e){let c=m(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,h.callConnectedTool)(b,a.server,a.name,c??void 0,d)}))}return c.length>e.length&&Object.assign(f,n(b)),f}async function k(a){let b=(await (0,h.listConnectedToolNames)(a)).map(a=>a.name);if(b.length)return`Tools on "${a}": ${b.join(", ")}.`;let c=await (0,h.listConnectedServerNames)();return c.length?`There is no server called "${a}". Connected: ${c.join(", ")}.`:"Nothing is connected."}let n=a=>({[f.TOOL_NAMES.tool_search]:(0,d.tool)({description:l[f.TOOL_NAMES.tool_search].description,inputSchema:l[f.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,8),e=await (0,h.findConnectedSchemas)(a.trim(),d);if(!e.length)return{tools:[],note:await k(a)};let f=d.filter(a=>!e.some(b=>b.name===a)),g=c.slice(8),i=[f.length?`Not on "${a}": ${f.join(", ")}.`:"",g.length?`Only 8 at a time — ask again for: ${g.join(", ")}.`:""].filter(Boolean);return{tools:e,...i.length?{note:i.join(" ")}:{}}}}),[f.TOOL_NAMES.tool_call]:(0,d.tool)({description:l[f.TOOL_NAMES.tool_call].description,inputSchema:l[f.TOOL_NAMES.tool_call].parameters,execute:async({server:b,tool:c,args:d},{abortSignal:e})=>(await (0,h.listConnectedToolNames)(b.trim())).some(a=>a.name===c.trim())?(0,h.callConnectedTool)(a,b.trim(),c.trim(),d??void 0,e):{status:"error",text:await k(b)}})});a.s(["createMcpTools",0,j]),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=a.i(569549),l=b([i,k]);[i,k]=l.then?(await l)():l;let m=a=>({...a,facts:a.facts.map(({saidAt:a,...b})=>a?{...b,said:(0,g.saidStamp)(a)}:b),factCount:a.facts.length}),n=a=>"user"===a?"Typed on the screen — there is no conversation behind it.":"bot"===a?"Saved by a bot during a job — there is no conversation behind it.":"The conversation it was saved in is not kept.",o=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.`:"";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:e.string().describe("Exactly as the listing writes it — the path, or one of the names in quotes after it.")}),execute:async({path:a})=>{let{notes:b}=await (0,i.readNotes)([a],{touch:c}),d=b[0];if(!d)return{note:`Nothing on the listing called ${a.trim()}.`};let e=o(d.facts.length);return e?{...m(d),note:e.trim()}:m(d)}}),[h.TOOL_NAMES.memory_remember]:(0,d.tool)({description:"Write to one note: facts, and the line the listing shows for it. The path is the key — a path not on the listing is created (with at least one fact), one that is gets amended.",inputSchema:e.object({path:e.string().describe("Exactly as the listing writes it, or a new path following the same convention."),facts:e.object({text:e.string().describe('One statement that stands on its own later — a date as a date, never "next week".'),replaces:e.number().int().nullish().describe("The id of the fact this replaces — from this note as handed back here or by `memory_recall`. Null if this is new. A fact that stopped being true is replaced rather than deleted, and so is a note saying the same thing twice: replacing keeps what changed on the record, deleting does not."),alwaysLoad:e.boolean().nullish().describe(`True carries this line into every call's instructions without opening its note — for what every call needs before any note is opened: what to call them, their language and register. At most ${f.MEMORY_LIMITS.carried}. Null leaves it; false makes a carried line an ordinary fact.`)}).array().nullish().describe("What to write under this note. Send everything that came up at once: one call is one pause in the conversation, three calls are three. Null when only naming it."),description:e.string().nullish().describe(`One line saying what this note is about, not what it currently says. Give it for a new note, or when the line no longer fits. Null leaves it; ${j.APP_NAMED_NOTES.join(", ")} keep their own line.`),aliases:e.string().array().nullish().describe('What the user calls this note out loud, in the language they say it — the words they would use to ask for it, not the facts inside. A note at people/yuri might be "Yuri" and "my wife". Replaces the set it has, so send the whole set. Null leaves it.')}),execute:async c=>{let d=c.path.trim(),e=await (0,i.resolveNotePath)(d),g=c.aliases??null,h=e??d,k=(0,j.isAppNamed)(h)?(0,j.appNoteLine)(h):c.description?.trim()||null,l=c.facts??[];if(!l.length&&!k&&!g)return{note:"Nothing to write: send facts, a line, names, or any of them."};if(!e&&!l.length)return{note:`Nothing on the listing called ${d}. A note comes into being with a fact — send at least one.`};let n=!e&&!(0,j.isMemoryPath)(d),p=n?{path:j.MEMORY_INBOX,description:(0,j.appNoteLine)(j.MEMORY_INBOX),facts:l}:{path:h,description:k,aliases:g,facts:l},q=await (0,i.writeNotes)([p],a,b),r=n?` Filed under ${p.path}: "${d}" is not a path this listing can carry. If that is not where it belongs, write it again under one that is.`:"",s=q.unnamed.length?` ${q.unnamed[0]} is new and has no line yet — the listing shows its first fact instead. Call again with \`description\` (one line about what it is) and \`aliases\` (the names they say for it).`:"",t=q.notLoaded.length?` All ${f.MEMORY_LIMITS.carried} carried lines are taken, so ${q.notLoaded.map(a=>`"${a}"`).join(", ")} saved as an ordinary fact. Say which carried line you would drop for it and let them choose.`:"",u=m(q.notes[0]);return{...u,note:`Saved. The listing in your instructions is from when this session opened and will not show this until the next one — the note below is current.${r}${s}${t}${o(u.factCount)}`}}}),[h.TOOL_NAMES.memory_conversation]:(0,d.tool)({description:"Open the conversation a fact was saved in, whole: what each side said, and which tools were used.",inputSchema:e.object({factId:e.number().int().describe("The id that came with the fact when its note was opened."),page:e.number().int().min(1).nullish().describe(`${f.MEMORY_CONVERSATION_PAGE} turns a page, oldest first. Null for the first.`)}),execute:async({factId:a,page:c})=>{let d=await (0,i.findFactCall)(a);if(!d)return{note:`No fact with id ${a}.`};if(!d.callId)return{note:n(d.source)};if(d.callId===b)return{note:"Said in this call — it is the conversation you are in."};let e=c??1,h=await (0,k.readCallConversation)(d.callId,e,f.MEMORY_CONVERSATION_PAGE);if(!h)return{note:n(d.source)};let j=Math.max(1,Math.ceil(h.total/f.MEMORY_CONVERSATION_PAGE));return e>j?{note:`That conversation has ${j} page${j>1?"s":""}.`}:{when:(0,g.callStamp)(h.startedAt),page:e,pages:j,conversation:(0,g.conversationLines)(h.turns)}}}),[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(m),note:e}}})})]),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 o=`Answer the question from the web. Lead with the answer, then
|
|
86
88
|
what supports it. Say plainly what you could not find or confirm — do not fill
|
|
87
89
|
the gap with a guess. Every number carries the date you saw it. Be brief: this
|
|
88
90
|
is read by another model, not by a person.`,p=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`Exa answered ${d.status}: ${(0,k.clip)((await d.text()).trim(),200)}`;let e=(await d.json()).results??[];return e.length?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"):"Nothing came back for that. Try other words, or open a page in the browser."}async function n(a,b,c){let{text:e,sources:f}=await (0,d.generateText)({model:a.model,tools:a.tools,system:o,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[e.trim(),h.length?`Sources:
|
|
89
|
-
${h.join("\n")}`:""].filter(Boolean).join("\n\n")}let q=async(a,b)=>{let c=await (0,j.readConfig)(i.EXA_API_KEY),d=a?.searchTools?{model:a.model,tools:a.searchTools}:null,l=c?(a,b)=>m(c,a,b):d?(a,b)=>n(d,a,b):null;return l?{[h.TOOL_NAMES.web_search]:(0,e.tool)({description:"Search the web and get back what the pages say, with their links. For a fact, a price, a date, what a page says. Not for a page that has to be clicked, filled, or signed into — that is the browser.",inputSchema:f.default.object({query:p}),execute:async({query:a},{abortSignal:c})=>{let d=AbortSignal.timeout(g.SEARCH.timeoutMs),e=c?AbortSignal.any([c,d]):d,f=await l(a,e).catch(a=>{if(c?.aborted)throw a;return d.aborted?`The search did not come back in ${g.SEARCH.timeoutMs/1e3}s. Ask something narrower, or open the page in the browser.`:`Search failed: ${(0,k.errorToString)(a)}. The browser is the other way in.`});return b.fold(f,"web-search")}})}:{}};a.s(["createSearchTool",0,q]),c()}catch(a){c(a)}},!1),451017,a=>{"use strict";var b=a.i(527990),c=a.i(723885),d=a.i(762008),e=a.i(762805);a.s(["createSkillTools",0,({skills:a,sandbox:f})=>{
|
|
91
|
+
${h.join("\n")}`:""].filter(Boolean).join("\n\n")}let q=async(a,b)=>{let c=await (0,j.readConfig)(i.EXA_API_KEY),d=a?.searchTools?{model:a.model,tools:a.searchTools}:null,l=c?(a,b)=>m(c,a,b):d?(a,b)=>n(d,a,b):null;return l?{[h.TOOL_NAMES.web_search]:(0,e.tool)({description:"Search the web and get back what the pages say, with their links. For a fact, a price, a date, what a page says. Not for a page that has to be clicked, filled, or signed into — that is the browser.",inputSchema:f.default.object({query:p}),execute:async({query:a},{abortSignal:c})=>{let d=AbortSignal.timeout(g.SEARCH.timeoutMs),e=c?AbortSignal.any([c,d]):d,f=await l(a,e).catch(a=>{if(c?.aborted)throw a;return d.aborted?`The search did not come back in ${g.SEARCH.timeoutMs/1e3}s. Ask something narrower, or open the page in the browser.`:`Search failed: ${(0,k.errorToString)(a)}. The browser is the other way in.`});return b.fold(f,"web-search")}})}:{}};a.s(["createSearchTool",0,q]),c()}catch(a){c(a)}},!1),451017,a=>{"use strict";var b=a.i(527990),c=a.i(723885),d=a.i(762008),e=a.i(762805);a.s(["createSkillTools",0,({skills:a,sandbox:f})=>({[d.TOOL_NAMES.load_skill]:(0,b.tool)({description:"Load one skill: its instructions, and the files that ship with it.",inputSchema:c.default.object({name:c.default.string().describe("Exact name from the Skills list. Do not guess names that are not on it.")}),execute:async({name:b},{messages:c})=>{let g=a.find(a=>a.name.toLowerCase()===b.toLowerCase());if(!g)return{error:`No skill named '${b}'.`,available:a.map(a=>a.name)};let h=`${g.path}/SKILL.md`;if(c.some(a=>Array.isArray(a.content)&&a.content.some(a=>{if("tool-result"!==a.type||a.toolName!==d.TOOL_NAMES.load_skill||"json"!==a.output.type)return!1;let b=a.output.value;return b?.skillDirectory===g.path&&"string"==typeof b.content})))return{skillDirectory:g.path,note:`Use the full '${g.name}' instructions already in your conversation. To check for changes on disk, read ${h} with the shell.`};let i=await f.readFile(h,"utf-8"),{body:j}=(0,e.splitFrontmatter)(i),k=await f.glob("**/*",{path:g.path,limit:50});return{skillDirectory:g.path,files:k,content:j}}})})])},500777,a=>a.a(async(b,c)=>{try{var d=a.i(912714),e=a.i(750227),f=a.i(47919),g=a.i(12208),h=a.i(723885),i=a.i(569572),j=a.i(875931),k=a.i(762008),l=a.i(176668),m=a.i(182248),n=b([j]);function o(a){return{...a,execute:(b,c)=>{let d=a.inputSchema.safeParse(b);if(!d.success)throw Error(h.default.prettifyError(d.error));return a.execute(d.data,c)}}}[j]=n.then?(await n)():n;let t={images:`${i.PATHS.artifacts}/images`,audio:`${i.PATHS.artifacts}/audio`,transcripts:`${i.PATHS.artifacts}/transcripts`,videos:`${i.PATHS.artifacts}/videos`};function p(a,b){let c=a.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,40),d=(0,g.format)(new Date,"yyyyMMdd-HHmmss");return`${d}${c?`-${c}`:""}.${b}`}async function q(a,b,c,d){let e=`${b}/${c}`;return await a.exec(`mkdir -p ${b}`),await a.writeFile(e,Buffer.from(d)),e}let u=a=>`${a}
|
|
90
92
|
Saved. Give the user this path — the file opens from the task row. Do not describe it back to them; they can open it.`,v=(a,b)=>a?.split("/")[1]?.split(";")[0]||b,w=["1:1","16:9","9:16","4:3","3:4"],x=async()=>{let a=await (0,j.resolveMediaRef)("image");if(!a)return null;let b=(0,j.buildImageModel)(a.ref,a.apiKey);return o({name:k.STUDIO_TOOLS.generate_image,description:"Draw an image and save it as a file in the workspace. What comes back is its path.",inputSchema:h.default.object({prompt:h.default.string().describe("What to draw, described: subject, style, mood, what is in frame. The image model does not see the job or the conversation, so nothing can be left implied."),aspectRatio:h.default.enum(w).nullish().describe("Aspect ratio. Null for square.")}),execute:async({prompt:a,aspectRatio:c},{sandbox:d,abortSignal:e})=>{let{image:g}=await (0,f.generateImage)({model:b,prompt:a,aspectRatio:c??"1:1",abortSignal:e}),h=await q(d,t.images,p(a,v(g.mediaType,"png")),g.uint8Array);return u(h)}})},y=async()=>{let a=await (0,j.resolveMediaRef)("speech");if(!a)return null;let b=(0,j.buildSpeechModel)(a.ref,a.apiKey);return o({name:k.STUDIO_TOOLS.generate_speech,description:"Read text aloud into an audio file in the workspace — something the user listens to or sends, not Thursday's voice. What comes back is its path.",inputSchema:h.default.object({text:h.default.string().min(1).max(4e3).describe("The words to read, up to 4000 characters. Longer pieces are read in parts, one call each."),voice:h.default.string().nullish().describe("A voice name the provider knows. Null for its default."),instructions:h.default.string().nullish().describe('How to read it — "slowly", "warm", "like a news anchor". Null for plain.')}),execute:async({text:a,voice:c,instructions:d},{sandbox:e,abortSignal:g})=>{let{audio:h}=await (0,f.generateSpeech)({model:b,text:a,voice:c??void 0,instructions:d??void 0,outputFormat:"mp3",abortSignal:g}),i=await q(e,t.audio,p(a.slice(0,60),h.format||"mp3"),h.uint8Array);return u(i)}})},z=async()=>{let a=await (0,j.resolveMediaRef)("transcription");if(!a)return null;let b=(0,j.buildTranscriptionModel)(a.ref,a.apiKey);return o({name:k.STUDIO_TOOLS.transcribe,description:"Turn an audio file — a recording, a voice memo, a meeting — into text. The transcript is saved as a file in the workspace; what comes back is its path and the text.",inputSchema:h.default.object({path:h.default.string().min(1).describe("The audio file: a path relative to the workspace, or an absolute one anywhere on this machine.")}),execute:async({path:a},{sandbox:c,abortSignal:g})=>{let h=await (0,d.readFile)(c.resolve(a)),i=await (0,f.transcribe)({model:b,audio:h,abortSignal:g}),j=i.segments.length?`
|
|
91
93
|
|
|
92
94
|
## Timeline
|
|
@@ -102,14 +104,22 @@ Every command is a new shell: \`cd\`, exported variables and an activated venv a
|
|
|
102
104
|
|
|
103
105
|
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.
|
|
104
106
|
|
|
105
|
-
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 i=!0===e.guide,j=(0,c.tool)({description:"Run a bash command.",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 d=await a.exec(b,{signal:c,env:e.env});return i?(i=!1,{...d,guide:h}):d}});if(!e.write)return{[f.TOOL_NAMES.bash]:j};let k=(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 e,f=a.resolve(c),h=(0,g.writeRefusal)(f);return h?h:(await a.writeFile(c,d),`Wrote ${(e=(0,b.relative)(a.cwd,f))&&!e.startsWith("..")?e:f} (${d.split("\n").length} lines)`)}});return{[f.TOOL_NAMES.bash]:j,[f.TOOL_NAMES.write_file]:k}}])},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,i=d.BOT_MEMORY_LISTED){let j=f(a),k=(0,c.join)(e.WORKSPACE,j),l=await (0,b.readdir)(k).catch(()=>[]),m=(await Promise.all(l.filter(a=>!a.startsWith(".")).map(async a=>{let d=await (0,b.stat)((0,c.join)(k,a)).catch(()=>null);return d?.isFile()?{name:a,changed:d.mtimeMs,bytes:d.size}:null}))).filter(a=>null!==a).sort((a,b)=>b.changed-a.changed),n=await Promise.all(m.slice(0,i).map(async({name:a,changed:b,bytes:d})=>({file:a,path:`${j}/${a}`,line:await h((0,c.join)(k,a)),at:new Date(b),bytes:d})));return{folder:j,entries:n,total:m.length}}async function h(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,"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(446957),m=a.i(821415),n=a.i(176668),o=a.i(293480),p=a.i(
|
|
107
|
+
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 i=!0===e.guide,j=(0,c.tool)({description:"Run a bash command.",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 d=await a.exec(b,{signal:c,env:e.env,timeoutMs:e.timeoutMs});return i?(i=!1,{...d,guide:h}):d}});if(!e.write)return{[f.TOOL_NAMES.bash]:j};let k=(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 e,f=a.resolve(c),h=(0,g.writeRefusal)(f);return h?h:(await a.writeFile(c,d),`Wrote ${(e=(0,b.relative)(a.cwd,f))&&!e.startsWith("..")?e:f} (${d.split("\n").length} lines)`)}});return{[f.TOOL_NAMES.bash]:j,[f.TOOL_NAMES.write_file]:k}}])},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,i=d.BOT_MEMORY_LISTED){let j=f(a),k=(0,c.join)(e.WORKSPACE,j),l=await (0,b.readdir)(k).catch(()=>[]),m=(await Promise.all(l.filter(a=>!a.startsWith(".")).map(async a=>{let d=await (0,b.stat)((0,c.join)(k,a)).catch(()=>null);return d?.isFile()?{name:a,changed:d.mtimeMs,bytes:d.size}:null}))).filter(a=>null!==a).sort((a,b)=>b.changed-a.changed),n=await Promise.all(m.slice(0,i).map(async({name:a,changed:b,bytes:d})=>({file:a,path:`${j}/${a}`,line:await h((0,c.join)(k,a)),at:new Date(b),bytes:d})));return{folder:j,entries:n,total:m.length}}async function h(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,"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(446957),m=a.i(821415),n=a.i(176668),o=a.i(293480),p=a.i(8412),q=a.i(987674),r=a.i(182248),s=a.i(221214),t=a.i(84929),u=b([g,h,i,s,t]);[g,h,i,s,t]=u.then?(await u)():u;let E=f.BOT_RUN.steps;async function v(a,b){var c,p,u;let v,y,H,I,J,K,L,M,N,O=b.depth??0,P=b.parent??null,Q=await (0,s.findJobBot)(a.bot.trim()),R=Q?.name??a.bot.trim(),S=a=>b.emit({...a,bot:R,parent:P});if(!Q)return void await S({type:"error",message:`No bot named "${a.bot}". Use a name from the list.`,failure:"fatal"});let T="askedBy"in a&&b.taskId?await (0,t.listBotThread)(b.taskId,R):[];if(Q.disabled&&"request"in a&&!T.length)return void await S({type:"error",message:`${Q.name} is switched off. Use a name from the list.`,failure:"fatal"});if(b={...b,desks:b.desks??A()},"messages"in a)N=a.messages;else{let c=T.length?`## ${a.askedBy} → ${R}: the next request
|
|
108
|
+
|
|
109
|
+
${a.request.trim()}${a.context?.trim()?`
|
|
110
|
+
|
|
111
|
+
## What ${a.askedBy} passes on
|
|
112
|
+
|
|
113
|
+
${a.context.trim()}`:""}`:(0,i.buildHandoff)({chain:a.chain,bots:[...a.above,R],did:a.context??null,part:a.request});N=[...D(T,b.taskId?await (0,t.listBorrowedTails)(b.taskId):void 0),{role:"user",content:c}],b.signal?.throwIfAborted(),await S({type:"request",content:c})}let U=await ((c=Q).provider&&c.model?(0,h.getTextModel)({provider:c.provider,model:c.model}):(0,h.resolveDefaultModel)().then(h.getTextModel)),V=b.taskId?await (0,t.findTask)(b.taskId):null,[W,X]=await Promise.all([b.taskId?(0,m.openJobScratch)(b.taskId,V?.label??"job"):null,(0,m.openBotFolder)(R)]),[Y,Z]=await Promise.all([(0,i.loadBotPrompt)(R,Q.systemPrompt,"askedBy"in a?{askedBy:a.askedBy,above:a.above,canBorrow:O<f.BOT_RUN.depth}:null,{scratch:W,own:X}),(0,g.loadTools)({target:"bot",bot:R,session:b.session??b.taskId,model:U})]),$=Math.min(await (0,h.compactBudget)(U.ref,Q.compactAt),("askedBy"in a?0:V?.contextBudget)||1/0),_={left:f.BOT_RUN.askBack},aa="askedBy"in a?function(a,b,c){let d={...a};delete d[k.TOOL_NAMES.ask_thursday];let{answer:f}=c;return f?{...d,[k.TOOL_NAMES.ask_back]:(0,e.tool)({description:j.askBackSpec.description,inputSchema:j.askBackSpec.parameters,execute:async({question:a})=>(b.left-=1,f(a))})}:d}(Z,_,b):Z,ab=O<f.BOT_RUN.depth?function(a,b){if(0===b.peers.length)return a;let c=new WeakMap,d={...a,[k.TOOL_NAMES.ask_bot]:(0,e.tool)({description:j.askBotSpec.description,inputSchema:j.askBotSpec.parameters,execute:async({bot:a,request:e,context:f},g)=>{let i=await (0,s.findJobBot)(a);if(!i)return`No bot named "${a}". Use a name from the list.`;if((a=i.name)===b.name||b.above.includes(a))return`${a} is already above you and waiting on this part. Use ask_back for a question, or pick another bot.`;let j=g.abortSignal??b.options.signal;return b.options.desks.run(b.name,a,j,async()=>{let i=b.options.taskId?(0,m.botBrowserSession)(b.options.taskId,a):null,k=[],l=c.get(g.messages);l||(l={messages:[...g.messages],answer:(0,r.PromiseChain)()},c.set(g.messages,l));let n=l;try{let c=await z({bot:a,request:e,context:f,askedBy:b.name,chain:b.chain,above:[...b.above,b.name]},{...b.options,signal:j,depth:b.depth+1,parent:g.toolCallId,session:i,notes:void 0,answer:c=>n.answer(async()=>{j?.throwIfAborted();let f=await C({model:b.model,instructions:b.instructions,tools:d,messages:n.messages,asked:{bot:a,request:e},question:c,signal:j});return n.messages.push({role:"user",content:`${a} asks about the part you handed over:
|
|
114
|
+
|
|
115
|
+
${c}`},{role:"assistant",content:f.text}),await b.emit({type:"answered",question:c,...f}),k.push({question:c,answer:f.text}),f.text})});return k.length?`${c}
|
|
106
116
|
|
|
107
|
-
${
|
|
117
|
+
${B(a,k)}`:c}catch(b){j?.throwIfAborted(),(0,o.publicError)([(0,h.modelErrorToString)(b),B(a,k)].filter(Boolean).join("\n\n"))}})}})};return d}(aa,{name:R,model:U.model,instructions:Y.text,peers:Y.peers,depth:O,chain:(0,i.chainOf)(N[0]),above:"askedBy"in a?a.above:[],options:b,emit:S}):aa,ac={compact:null,interjections:[]},ad=(p=f.BOT_RUN.silenceMs,y=new AbortController,H=0,I=!1,J=()=>{clearTimeout(v),v=void 0,I||H>0||(v=setTimeout(()=>{y.abort(new DOMException(`The model sent nothing for ${Math.round(p/6e4)} minutes.`,"TimeoutError"))},p))},{signal:y.signal,touch:J,hold:()=>{H+=1,J()},release:()=>{H=Math.max(0,H-1),J()},end:()=>{I=!0,J()}}),ae=0,af=new d.ToolLoopAgent({model:U.model,instructions:Y.text,tools:ab,stopWhen:[(0,d.stepCountIs)(E),F,(0,d.hasToolCall)(k.TOOL_NAMES.ask_thursday)],prepareStep:async({stepNumber:a,steps:c,messages:d})=>{let e=a<E-1?{}:{activeTools:[k.TOOL_NAMES.answer],toolChoice:{type:"tool",toolName:k.TOOL_NAMES.answer}};!e.activeTools&&_.left<=0&&(e={...e,activeTools:Object.keys(ab).filter(a=>a!==k.TOOL_NAMES.ask_back)});let f=c.at(-1)?.usage.inputTokens??0,g=Math.max(f,d.reduce((a,b)=>a+(0,q.estimateTokens)("string"==typeof b.content?b.content:JSON.stringify(b.content))+4,0));ae=g;let h=d;if(g>$&&d.length>2){ad.hold();let a=await x(U.model,ab,d,{signal:b.signal,budget:$,instructions:Y.text}).finally(ad.release);n.logger.debug(`compacted ${d.length} messages at ${g} tokens (budget ${$})`);let c=`${a.text}${await w(V?.id??null,d,W)}`;ac.compact={type:"compact",text:c,usage:a.usage,messages:d.length,tokens:g},h=[d[0],{role:"user",content:c}]}let i=a>0?b.notes?.()??[]:[];return(i.length&&(ac.interjections.push(...i),h=[...h,...i.map(a=>({role:"user",content:a}))]),h===d)?e:{...e,messages:h}}}),ag=(K=[],L=[],M=!1,{push(a){let b=L.shift();b?b(a):K.push(a)},take(){let a=K.shift();return a?Promise.resolve(a):M?Promise.resolve(null):new Promise(a=>L.push(a))},end(){for(let a of(M=!0,L.splice(0)))a(null)}}),ah=b.signal?AbortSignal.any([b.signal,ad.signal]):ad.signal;ad.touch();let ai=await af.stream({messages:N,abortSignal:ah,onStepEnd:a=>ag.push({messages:a.response.messages,usage:G(a.usage)})}),aj="",ak=null,al=null,am=null,an=-1,ao=null,ap=new Set,aq=a=>{let b=(0,h.modelFailureOf)(a),c=(0,h.modelErrorToString)(a);if("overflow"!==b)return{type:"error",message:c,failure:b};let d=Math.floor(Math.min($,ae||$)*f.BOT_RUN.overflowShrink);return{type:"error",message:c,failure:b,budget:Math.max(l.COMPACT_AT_MIN,d)}};ah.addEventListener("abort",()=>ag.end(),{once:!0});try{for await(let a of ai.fullStream)switch(ad.touch(),a.type){case"start-step":for(let a of(an+=1,ac.compact&&(await S(ac.compact),ac.compact=null),ac.interjections.splice(0)))await S({type:"interjection",text:a});break;case"text-delta":aj+=a.text;break;case"text-end":{let a=aj.trim();if(aj="",!a)break;ak=a,await S({type:"text",text:a});break}case"tool-call":if(a.toolName===k.TOOL_NAMES.ask_thursday){let b=a.input;al={id:a.toolCallId,question:String(b.question??""),options:(0,t.optionsOf)(b.options)}}else if(a.toolName===k.TOOL_NAMES.answer){let b=a.input;am={text:String(b.result??"").trim(),stopped:an>=E-1}}a.providerExecuted||a.toolName===k.TOOL_NAMES.ask_thursday||(ap.add(a.toolCallId),ad.hold()),await S({type:"tool",id:a.toolCallId,name:a.toolName,input:a.input});break;case"tool-result":ap.delete(a.toolCallId)&&ad.release(),a.toolName===k.TOOL_NAMES.answer&&am&&!(0,j.answerAccepted)(a.output)&&(am={text:`${am.text}
|
|
108
118
|
|
|
109
|
-
${
|
|
119
|
+
${u=a.output,"string"==typeof u?u:u&&"object"==typeof u&&"value"in u?"string"==typeof u.value?u.value:JSON.stringify(u.value??""):JSON.stringify(u??"")}`,stopped:!0}),await S({type:"tool-result",id:a.toolCallId,name:a.toolName,output:a.output});break;case"tool-error":ap.delete(a.toolCallId)&&ad.release(),await S({type:"tool-result",id:a.toolCallId,name:a.toolName,output:(0,h.modelErrorToString)(a.error),error:!0});break;case"finish-step":{ao=a.finishReason;let b=await ag.take();b&&await S({type:"step",...b,budget:$});break}case"abort":if(b.signal?.aborted)return;await S({type:"error",message:a.reason??"The model stopped sending.",failure:"transient"});return;case"error":await S(aq(a.error));return}}finally{ag.end(),ad.end()}try{await ai.response}catch(a){if(b.signal?.aborted)return;await S(aq(a));return}al?await S({type:"waiting",...al}):am?await S({type:"answer",...am}):"content-filter"===ao?await S({type:"error",message:"The provider's content filter stopped the response.",failure:"fatal"}):await S({type:"answer",text:ak??"Stopped without handing anything back.",stopped:null===ak||"length"===ao||an>=E-1})}let F=({steps:a})=>a.at(-1)?.toolResults.some(a=>a.toolName===k.TOOL_NAMES.answer&&(0,j.answerAccepted)(a.output))??!1;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,m.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
120
|
|
|
111
121
|
Files this job has on disk now — open one rather than fetching again what is in it:
|
|
112
|
-
${i.join("\n")}`}catch(a){return n.logger.warn("files under the summary could not be listed",a),""}}async function
|
|
122
|
+
${i.join("\n")}`}catch(a){return n.logger.warn("files under the summary could not be listed",a),""}}async function x(a,b,c,e){let f;try{return await y(a,b,c,e)}catch(a){if(e.signal?.aborted)throw a;f=a}if("overflow"===(0,h.modelFailureOf)(f)){let g=(0,d.pruneMessages)({messages:c,toolCalls:"before-last-4-messages",emptyMessages:"remove"});try{return await y(a,b,g,e)}catch(a){if(e.signal?.aborted)throw a;f=a}}throw Error(`Could not compact the context (${(0,h.modelErrorToString)(f)}).`,{cause:f})}async function y(a,b,c,e){let g,{text:h,usage:i}=await (0,d.generateText)({model:a,system: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 — the job, the call it came from, and anything handed over with it — 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
123
|
|
|
114
124
|
Cover all of it, and prefer a fact over a description of a fact:
|
|
115
125
|
|
|
@@ -122,9 +132,9 @@ Cover all of it, and prefer a fact over a description of a fact:
|
|
|
122
132
|
|
|
123
133
|
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 Object.assign(Error("The summary of the context came back empty, so there is nothing to carry on from."),{isRetryable:!0});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
134
|
|
|
125
|
-
${j}`,usage:
|
|
135
|
+
${j}`,usage:G(i)}}let G=a=>({input:a.inputTokens??0,output:a.outputTokens??0});async function z(a,b){let c="",d=null;return await v(a,{...b,emit:async a=>{a.parent===(b.parent??null)&&"answer"===a.type&&(c=a.stopped?`${a.text}
|
|
126
136
|
|
|
127
|
-
(As far as they got — they stopped before finishing.)`:a.text),"error"===a.type&&(d=a.message),await b.emit(a)}}),d&&(0,o.publicError)(d),c}async function
|
|
137
|
+
(As far as they got — they stopped before finishing.)`:a.text),a.parent===(b.parent??null)&&"error"===a.type&&(d=a.message),await b.emit(a)}}),b.signal?.throwIfAborted(),d&&(0,o.publicError)(d),c}function A(){let a=(0,p.createKeyedLock)(),b=new Map,c=new Set,d=(a,c,e=new Set)=>a===c||!e.has(a)&&(e.add(a),[...b.get(a)?.keys()??[]].some(a=>d(a,c,e)));return{async run(e,f,g,h){g?.throwIfAborted(),d(f,e)&&(0,o.publicError)(`${f} is waiting on your work. Finish this part before asking them, or choose another bot.`);let i=b.get(e)??new Map;b.set(e,i),i.set(f,(i.get(f)??0)+1);let j=a(f,async()=>(g?.throwIfAborted(),h()));c.add(j);try{return await j}finally{c.delete(j);let a=(i.get(f)??1)-1;a?i.set(f,a):i.delete(f),i.size||b.delete(e)}},async settle(){for(;c.size;)await Promise.allSettled([...c])}}}function B(a,b){return b.map(({question:b,answer:c})=>`(On the way ${a} asked you: "${b}" — you answered: "${c}")`).join("\n")}async function C(a){try{let b,c,{text:e,usage:g}=await (0,d.generateText)({model:a.model,system:a.instructions,tools:a.tools,toolChoice:"none",messages:[...a.messages,{role:"user",content:(b=a.asked,c=a.question,`You handed one part of your job to ${b.bot}:
|
|
128
138
|
|
|
129
139
|
> ${b.request.trim()}
|
|
130
140
|
|
|
@@ -132,13 +142,13 @@ Before going on, they ask you:
|
|
|
132
142
|
|
|
133
143
|
> ${c.trim()}
|
|
134
144
|
|
|
135
|
-
Answer from what you already have — the request as it reached you, the call it came out of, what you found before asking them. A few lines, plain text, and nothing else: no tools run here. If it is not in what you have, say so rather than guess, and say which way to go without it.`)}],abortSignal:a.signal,timeout:f.BOT_RUN.silenceMs});return{text:e.trim()||"They had nothing to add. Go on with your best reading, and say what you assumed in what you hand back.",usage:
|
|
145
|
+
Answer from what you already have — the request as it reached you, the call it came out of, what you found before asking them. A few lines, plain text, and nothing else: no tools run here. If it is not in what you have, say so rather than guess, and say which way to go without it.`)}],abortSignal:a.signal,timeout:f.BOT_RUN.silenceMs});return{text:e.trim()||"They had nothing to add. Go on with your best reading, and say what you assumed in what you hand back.",usage:G(g)}}catch(b){if(a.signal?.aborted)throw b;return n.logger.warn(`ask_back: ${(0,h.modelErrorToString)(b)}`),{text:`No answer came back (${(0,h.modelErrorToString)(b)}). Go on with your best reading, and say what you assumed in what you hand back.`,usage:l.NO_TOKENS}}}function D(a,b=new Map){let c=new Set;for(let b of a)if(("tool"===b.role||"assistant"===b.role)&&"string"!=typeof b.content)for(let a of b.content)"tool-result"===a.type&&c.add(a.toolCallId);let d=[],e=[];for(let f of a){if(e.length&&"tool"===f.role){d.push({...f,content:[...e,...f.content]}),e=[];continue}e.length&&(d.push({role:"tool",content:e}),e=[]),d.push(f),"assistant"===f.role&&"string"!=typeof f.content&&(e=f.content.flatMap(a=>"tool-call"!==a.type||c.has(a.toolCallId)?[]:[{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:{type:"text",value:function(a,b){let c=a.toolName===k.TOOL_NAMES.ask_bot?b.get(a.toolCallId):void 0;return c?`No result: the run was stopped before ${c.bot} answered, and they are not working on it any more. What they had written by then:
|
|
136
146
|
|
|
137
147
|
${c.tail}
|
|
138
148
|
|
|
139
|
-
Check what they did before relying on it, then finish the part yourself or hand them what is left.`:"No result: the run was stopped before this call returned. Check what it did before relying on it."}(a,b)}}]))}return e.length&&d.push({role:"tool",content:e}),d},"runBot",0,
|
|
149
|
+
Check what they did before relying on it, then finish the part yourself or hand them what is left.`:"No result: the run was stopped before this call returned. Check what it did before relying on it."}(a,b)}}]))}return e.length&&d.push({role:"tool",content:e}),d}a.s(["createBotDesks",0,A,"resumeThread",0,D,"runBot",0,v]),c()}catch(a){c(a)}},!1),674986,a=>a.a(async(b,c)=>{try{var d=a.i(203469),e=a.i(569572),f=a.i(875931),g=a.i(735502),h=a.i(762008),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(654034),q=a.i(446957),r=a.i(84929),s=b([f,g,i,p,r]);[f,g,i,p,r]=s.then?(await s)():s;let I=globalThis.__botRuns??=new Map,J=globalThis.__botTaskLock??=(0,o.createKeyedLock)(),K=globalThis.__botResumes??=new Map;async function t(a){let{from:b,...c}=a,d=c.callId?await (0,i.listCallTurns)(c.callId,g.OPENING_TURNS):[],e=(0,g.buildTaskOpening)({bot:c.bot,request:c.request,conversation:d,from:b}),f=await (0,r.insertTask)({...c,opening:e});return E(f.id,{bot:c.bot,messages:[{role:"user",content:e}]}),f.id}async function u(a,b,c){let d=c?(0,q.tagSpeaker)(c,b):b;return J(a,async()=>{let b=await (0,r.findTask)(a);b||(0,n.publicError)("No such job.");let c=I.get(a);if(c&&"running"===b.status&&c.note(d))return void m.logger.debug(`task ${a}: interjection queued`);c&&(c.stop.abort(),await c.done),z(a);let e=await (0,r.listThread)(a),{reply:f,as:g}=function(a,b,c){var d;let e,f,g="waiting"===a.status?a.pending:null,i=g?.toolCallId?(d=g.toolCallId,e=new Set(c.flatMap(a=>"tool"===a.role?a.content.flatMap(a=>"tool-result"===a.type?[a.toolCallId]:[]):[])),f=c.findLast(a=>"assistant"===a.role&&"string"!=typeof a.content&&a.content.some(a=>"tool-call"===a.type&&a.toolCallId===d)),(f?.role==="assistant"&&"string"!=typeof f.content?f.content.flatMap(a=>"tool-call"===a.type&&a.toolName===h.TOOL_NAMES.ask_thursday?[a.toolCallId]:[]):[d]).filter(a=>!e.has(a))):[];return i.length?{as:"answer",reply:{role:"tool",content:i.map(a=>({type:"tool-result",toolCallId:a,toolName:h.TOOL_NAMES.ask_thursday,output:{type:"text",value:b}}))}}:{as:"running"===a.status?"interruption":"waiting"===a.status?"answer":"follow-up",reply:{role:"user",content:b}}}(b,d,e);m.logger.debug(`task ${a}: ${g}`),await (0,r.upsertMessage)(a,await (0,r.lastSeq)(a)+1,{bot:null,parent:null,...f}),await (0,r.updateTask)(a,{status:"running",outcome:null,pending:null,seen:!1,endedAt:null}),E(a,{bot:b.bot,messages:(0,p.resumeThread)([...e,f],await (0,r.listBorrowedTails)(a))})})}async function v(a){return J(a,async()=>{let b=await (0,r.findTask)(a);b||(0,n.publicError)("No such job."),b.endedAt&&(0,n.publicError)("That job has already ended."),z(a);let c=I.get(a);c?.stop.abort(),await (0,r.updateTask)(a,{status:"failed",outcome:"Cancelled.",pending:null,seen:!0,endedAt:new Date}),await c?.done,await (0,k.closeJobShell)(a)})}async function w(a){return J(a,()=>x(a))}async function x(a){let b=await (0,r.findTask)(a);z(a);let c=I.get(a);c?.stop.abort(),await c?.done,await (0,k.closeJobShell)(a);let d=await (0,r.deleteTask)(a);return d&&b&&await (0,k.removeJobScratch)(a,b.label),d}async function y(){let a=0;for(let b of(await (0,r.listTaskFolders)()))("done"===b.status||"failed"===b.status)&&await J(b.id,async()=>{let c=await (0,r.findTask)(b.id);(c?.status==="done"||c?.status==="failed")&&await x(b.id)&&(a+=1)});return a}function z(a){clearTimeout(K.get(a)),K.delete(a)}async function A(a){d.presence.watching&&await J(a,async()=>{let b=await (0,r.findTask)(a);if(!b||"waiting"!==b.status||!b.pending?.auto||I.has(a))return;m.logger.debug(`task ${a}: picking back up`);let c=await (0,r.listThread)(a);await (0,r.updateTask)(a,{status:"running",outcome:null,pending:null,seen:!1,endedAt:null}),E(a,{bot:b.bot,messages:(0,p.resumeThread)(c,await (0,r.listBorrowedTails)(a))})})}async function B(a,b){let c=await (0,r.countStopsSinceSpoken)(a),d=c<e.BOT_RUN.autoResumes,f=e.BOT_RUN.retryAfterMs,g=d&&b.retry?f[Math.min(c,f.length-1)]:0;await C(a,(0,r.stopNote)(b.why)).catch(b=>m.logger.warn(`task ${a}: stop not written`,b)),await D(a,{status:"waiting",outcome:d?`${b.why} ${g?`It tries again in ${L(g)}.`:"It picks back up by itself."}`:`${b.why} It has stopped ${c+1} times in a row, so it waits for you. Everything it had done is still here.`,pending:{toolCallId:null,options:[q.TASK_CONTINUE],...d?{auto:!0,retryAt:Date.now()+g}:{}},...b.budget?{contextBudget:b.budget}:{},seen:!1,endedAt:null}),d&&(z(a),K.set(a,setTimeout(()=>{K.delete(a),A(a).catch(b=>m.logger.error(`task ${a}: resume`,b))},Math.max(0,g))))}globalThis.__botPausing??={current:Promise.resolve()};let L=a=>a<6e4?`${Math.round(a/1e3)} seconds`:`${Math.round(a/6e4)} minutes`;async function C(a,b){await (0,r.upsertMessage)(a,await (0,r.lastSeq)(a)+1,{bot:null,parent:null,role:"user",content:b,note:!0})}async function D(a,b){for(let c of[1e3,3e3,null])try{await (0,r.updateTask)(a,b);return}catch(b){if(null===c)throw b;m.logger.warn(`task ${a}: ending not written, trying again`,b),await new Promise(a=>setTimeout(a,c))}}function E(a,b){let c=new AbortController,d=()=>{},e=new Promise(a=>{d=a}),f=[];I.set(a,{stop:c,done:e,note:b=>!!I.has(a)&&(f.push(b),!0)}),F(a,b,c.signal,f).catch(b=>{m.logger.error(`task ${a}`,b)}).finally(d)}class M{taskId;seq;steps;closed;constructor(a,b){this.taskId=a,this.steps=new Map,this.closed=!1,this.seq=b}close(){this.closed=!0}async note(a){await (0,r.upsertMessage)(this.taskId,++this.seq,{bot:null,parent:null,role:"user",content:a,note:!0})}step(a){let b=`${a.bot} ${a.parent??""}`,c=this.steps.get(b);return c||(c={assistant:null,tool:null,parts:{assistant:[],tool:[]}},this.steps.set(b,c)),c}write(a,b,c,d={}){let e={bot:b.bot,parent:b.parent,role:c.role,content:c.content,compact:d.compact??!1,note:d.note??!1};return(0,r.upsertMessage)(this.taskId,a,e)}async on(a){if(this.closed)return;let b=this.step(a);switch(a.type){case"request":return this.write(++this.seq,a,{role:"user",content:a.content});case"text":return b.assistant??=++this.seq,b.parts.assistant.push({type:"text",text:a.text}),this.write(b.assistant,a,{role:"assistant",content:b.parts.assistant});case"tool":return b.assistant??=++this.seq,b.parts.assistant.push({type:"tool-call",toolCallId:a.id,toolName:a.name,input:a.input}),this.write(b.assistant,a,{role:"assistant",content:b.parts.assistant});case"tool-result":return b.assistant??=++this.seq,b.tool??=++this.seq,b.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.write(b.tool,a,{role:"tool",content:b.parts.tool});case"step":{let c=[b.assistant,b.tool];this.steps.delete(`${a.bot} ${a.parent??""}`);let d=new Set;for(let[b,e]of a.messages.entries()){let f=c[b]??++this.seq;d.add(f),await this.write(f,a,e)}let e=c.filter(a=>null!==a&&!d.has(a));e.length&&await (0,r.deleteMessages)(this.taskId,e);return}case"compact":return this.write(++this.seq,a,{role:"user",content:a.text},{compact:!0,note:!0});case"interjection":return this.write(++this.seq,a,{role:"user",content:a.text});default:return}}}async function F(a,b,c,g){let h=new M(a,await (0,r.lastSeq)(a)),i=(0,p.createBotDesks)(),l=null,n=null;try{await (0,p.runBot)(b,{signal:c,taskId:a,desks:i,notes:()=>g.splice(0),emit:async b=>{await h.on(b),"step"===b.type&&await (0,r.addTaskUsage)(a,b.usage,b.parent?null:{tokens:b.usage.input,budget:b.budget}),("compact"===b.type||"answered"===b.type)&&await (0,r.addTaskUsage)(a,b.usage),b.parent||("waiting"===b.type?l={status:"waiting",outcome:b.question,pending:{toolCallId:b.id,options:b.options}}:"answer"===b.type?l=b.stopped?{status:"waiting",outcome:b.text,pending:{toolCallId:null,options:[q.TASK_CONTINUE]}}:{status:"done",outcome:b.text,pending:null}:"error"===b.type&&(n={message:b.message,failure:b.failure,budget:b.budget},l={status:"failed",outcome:G(b.message),pending:null}))}})}catch(a){n={message:(0,f.modelErrorToString)(a),failure:(0,f.modelFailureOf)(a)},l={status:"failed",outcome:G(n.message),pending:null}}finally{await i.settle(),h.close(),I.delete(a)}if(c.aborted)return;let o=l??{status:"failed",outcome:"Stopped without handing anything back.",pending:null},s=n&&"fatal"!==n.failure?n:null;try{s?await B(a,{why:"overflow"===s.failure?`The model refused the context as too long (${s.message}); it is compacted before going on.`:`The model call failed (${s.message}).`,retry:"transient"===s.failure,budget:s.budget}):("failed"===o.status&&await h.note(`The run stopped here: ${n?.message??o.outcome}`).catch(b=>m.logger.warn(`task ${a}: break not written`,b)),await D(a,{...o,seen:!1,endedAt:"waiting"===o.status?null:new Date}))}catch(b){m.logger.error(`task ${a}: could not record how it ended`,b);return}(0,k.pruneJobFiles)();let t=await (0,r.findTask)(a);if(t){if(g.length){let b=g.splice(0).join("\n\n");m.logger.debug(`task ${a}: interjection after the run ended — resuming`),u(a,b).catch(b=>{m.logger.error(`task ${a}: late interjection`,b)});return}if(!s&&(await H(t.label,o),"done"===o.status)){var v;let b,c=(v=o.outcome,(b=(0,j.pathsIn)(v)).find(a=>a.startsWith(`${e.PATHS.artifacts}/`))??b[0]??null);c&&d.appEvents.emit({type:"artifact",taskId:a,label:t.label,path:c})}}}function G(a){return`The run broke: ${a}
|
|
140
150
|
|
|
141
|
-
Everything it had done is still here — answer to pick it back up.`}async function G(a,b){if(0!==d.appEventStream.watchers&&await (0,i.isAnyCallLive)())return;let c="waiting"===b.status?`${a} — needs you`:a;(0,l.desktopNotify)(c,b.outcome)}a.s(["answerTask",0,u,"cancelTask",0,v,"removeFinishedTasks",0,x,"removeTask",0,w,"startTask",0,t]),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;staticClient;lastAuthorizationUrl;constructor(a,b,c,d,e,f){this.store=a,this.serverName=b,this.oauth=c,this.callbackUrl=d,this.clientName=e,this.staticClient=f}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.staticClient??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;idleTtlMs;callbackUrl;clientName;constructor(a,b){this.store=a,this.sessions=new Map,this.connecting=new Map,this.callbackUrl=b.callbackUrl,this.idleTtlMs=b.idleTtlMs??18e5,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),/\b40[13]\b/.test(g)&&/OAuth|register/i.test(g)&&(0,k.isRemoteConfig)(f.config)&&!f.config.oauthClient?"This server does not allow automatic client registration. Register an OAuth app with the provider and add its client ID and secret.":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){let b=(0,k.isRemoteConfig)(a.config)?a.config.oauthClient:void 0;return new n(this.store,a.name,a.oauth??{},this.callbackUrl,this.clientName,b&&{client_id:b.clientId,client_secret:b.clientSecret})}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)},this.idleTtlMs);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(),oauthClient:b.z.object({clientId:b.z.string().min(1),clientSecret:b.z.string().optional()}).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),h=a.i(569572),i=a.i(184838),j=a.i(714428),k=a.i(8412),l=a.i(661210),m=b([i]);[i]=m.then?(await m)():m;let E=(0,k.createKeyedLock)(),F=()=>g.appEvents.emit({type:"memory"});async function n(a,b,c={}){let[d]=await i.database.insert(j.memoryNoteTable).values({path:a,description:b,ownedByUser:c.ownedByUser??!1}).onConflictDoNothing({target:j.memoryNoteTable.path}).returning();return d&&F(),d??null}async function o(a,b){let[c]=await i.database.update(j.memoryNoteTable).set({...b,updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,a)).returning();return c&&F(),c??null}async function p(a){let b=await i.database.delete(j.memoryNoteTable).where((0,d.eq)(j.memoryNoteTable.id,a)).returning({id:j.memoryNoteTable.id});return b.length>0&&F(),b.length>0}async function q(a,b){let[c]=await i.database.insert(j.memoryFactTable).values({noteId:a,text:b,source:"user"}).returning();return await t(a),F(),c}async function r(a,b,c){let e,f=await (e=()=>i.database.transaction(async e=>{let f=await e.update(j.memoryFactTable).set({isLatest:!1}).where((0,d.and)((0,d.eq)(j.memoryFactTable.id,b),(0,d.eq)(j.memoryFactTable.noteId,a),(0,d.eq)(j.memoryFactTable.isLatest,!0))).returning({id:j.memoryFactTable.id});if(0===f.length)return null;let[g]=await e.insert(j.memoryFactTable).values({noteId:a,text:c,source:"user"}).returning();return await e.update(j.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,a)),g}),E("memory",e));return f&&F(),f}async function s(a,b){let c=await i.database.delete(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.id,b),(0,d.eq)(j.memoryFactTable.noteId,a))).returning({id:j.memoryFactTable.id});return c.length>0&&(await t(a),F()),c.length>0}function t(a){return i.database.update(j.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,a))}async function u(){for(let a of l.MEMORY_ALWAYS_LISTED){let b=l.MEMORY_PATHS.find(b=>b.path===a)?.of??a;await i.database.insert(j.memoryNoteTable).values({path:a,description:b}).onConflictDoUpdate({target:j.memoryNoteTable.path,set:{description:b}})}}async function v(a){let b=a.map(a=>a.trim()).filter(Boolean),c=[],e=[];if(!b.length)return{found:c,missing:e};let f={id:j.memoryNoteTable.id,path:j.memoryNoteTable.path,description:j.memoryNoteTable.description},g=await i.database.select(f).from(j.memoryNoteTable).where((0,d.inArray)(j.memoryNoteTable.path,b)),h=new Map(g.map(a=>[a.path.toLowerCase(),a]));if(b.some(a=>!h.has(a.toLowerCase()))){let a=await i.database.select({...f,aliases:j.memoryNoteTable.aliases}).from(j.memoryNoteTable),b=(a,b)=>{let c=a.trim().toLowerCase();c&&!h.has(c)&&h.set(c,b)};for(let c of a)b(c.path,c);for(let c of a)for(let a of(b(c.path.slice(c.path.indexOf("/")+1),c),c.aliases??[]))b(a,c)}let k=new Set;for(let a of b){let b=h.get(a.toLowerCase());if(!b){e.push(a);continue}k.has(b.id)||(k.add(b.id),c.push(b))}return{found:c,missing:e}}async function w(a){let{found:b}=await v([a]);return b[0]?.path??null}async function x(a,b={}){let{found:c,missing:g}=await v(a);if(!c.length)return{notes:[],missing:g};let h=c.map(a=>a.id),k=await i.database.select({id:j.memoryFactTable.id,noteId:j.memoryFactTable.noteId,text:j.memoryFactTable.text,alwaysLoad:j.memoryFactTable.alwaysLoad,source:j.memoryFactTable.source,createdAt:j.memoryFactTable.createdAt,saidAt:j.callTable.startedAt}).from(j.memoryFactTable).leftJoin(j.callTable,(0,d.eq)(j.memoryFactTable.callId,j.callTable.id)).where((0,d.and)((0,d.eq)(j.memoryFactTable.isLatest,!0),(0,d.inArray)(j.memoryFactTable.noteId,h))).orderBy((0,e.asc)(j.memoryFactTable.id));return!1!==b.touch&&await i.database.update(j.memoryNoteTable).set({hits:f.sql`${j.memoryNoteTable.hits} + 1`,lastReadAt:new Date}).where((0,d.inArray)(j.memoryNoteTable.id,h)),{notes:c.map(a=>({path:a.path,description:a.description,facts:k.filter(b=>b.noteId===a.id).map(a=>({id:a.id,text:a.text,...a.saidAt?{saidAt:a.saidAt}:{}}))})),missing:g}}(0,d.inArray)(j.memoryNoteTable.path,l.MEMORY_ALWAYS_LISTED);let G=a=>a.toLowerCase().replace(/[\s.,!?…·'"`]/g,"");async function y(a,b,c=null){let e,g=[],k=[],l=[];await (e=()=>i.database.transaction(async e=>{let[i]=await e.select({count:f.sql`count(*)`}).from(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.alwaysLoad,!0),(0,d.eq)(j.memoryFactTable.isLatest,!0))),m=h.MEMORY_LIMITS.carried-Number(i?.count??0),n=(a,b)=>!!a&&(m>0?(m-=1,!0):(l.push(b),!1));for(let f of a){let a,h=f.path.trim();if(!h)continue;k.push(h);let i=f.description?.trim(),l=f.aliases?.map(a=>a.trim()).filter(Boolean),o=(f.facts??[]).map(a=>({...a,text:a.text.trim()})).filter(a=>a.text),[p]=await e.select({id:j.memoryNoteTable.id}).from(j.memoryNoteTable).where((0,d.eq)(j.memoryNoteTable.path,h));if(p)a=p.id,(i||l)&&await e.update(j.memoryNoteTable).set({...i?{description:i}:{},...l?{aliases:l}:{},updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,a));else{let[b]=await e.insert(j.memoryNoteTable).values({path:h,description:i??o[0]?.text.slice(0,80)??h,...l?{aliases:l}:{}}).returning({id:j.memoryNoteTable.id});a=b.id,i||g.push(h)}if(!o.length)continue;let q=await e.select({id:j.memoryFactTable.id,text:j.memoryFactTable.text,alwaysLoad:j.memoryFactTable.alwaysLoad}).from(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.noteId,a),(0,d.eq)(j.memoryFactTable.isLatest,!0))),r=new Map(q.map(a=>[G(a.text),a])),s=async(a,b,c)=>{if(b===a.alwaysLoad)return;let f=b?n(!0,c):(m+=1,!1);f!==a.alwaysLoad&&(await e.update(j.memoryFactTable).set({alwaysLoad:f}).where((0,d.eq)(j.memoryFactTable.id,a.id)),a.alwaysLoad=f)};for(let f of o){if(null!=f.replaces){let[g]=await e.select({id:j.memoryFactTable.id,text:j.memoryFactTable.text,alwaysLoad:j.memoryFactTable.alwaysLoad}).from(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.id,f.replaces),(0,d.eq)(j.memoryFactTable.noteId,a),(0,d.eq)(j.memoryFactTable.isLatest,!0)));if(g){if(G(g.text)===G(f.text)){await s(g,f.alwaysLoad??g.alwaysLoad,f.text),r.set(G(g.text),g);continue}await e.update(j.memoryFactTable).set({isLatest:!1}).where((0,d.eq)(j.memoryFactTable.id,g.id)),r.delete(G(g.text)),g.alwaysLoad&&(m+=1);let[h]=await e.insert(j.memoryFactTable).values({noteId:a,text:f.text,source:b,callId:c,alwaysLoad:n(f.alwaysLoad??g.alwaysLoad,f.text)}).returning({id:j.memoryFactTable.id,alwaysLoad:j.memoryFactTable.alwaysLoad});r.set(G(f.text),{...h,text:f.text});continue}}let g=r.get(G(f.text));if(g){null!=f.alwaysLoad&&await s(g,f.alwaysLoad,f.text);continue}let[h]=await e.insert(j.memoryFactTable).values({noteId:a,text:f.text,source:b,callId:c,alwaysLoad:n(!0===f.alwaysLoad,f.text)}).returning({id:j.memoryFactTable.id,alwaysLoad:j.memoryFactTable.alwaysLoad});r.set(G(f.text),{...h,text:f.text})}await e.update(j.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,a))}}),E("memory",e));let{notes:m}=await x(k,{touch:!1});return F(),{notes:m,unnamed:g,notLoaded:l}}async function z(a,b,c){let e,g=await (e=()=>i.database.transaction(async e=>{if(c){let[a]=await e.select({count:f.sql`count(*)`}).from(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.alwaysLoad,!0),(0,d.eq)(j.memoryFactTable.isLatest,!0)));if(Number(a?.count??0)>=h.MEMORY_LIMITS.carried)return"full"}let[g]=await e.update(j.memoryFactTable).set({alwaysLoad:c}).where((0,d.and)((0,d.eq)(j.memoryFactTable.id,b),(0,d.eq)(j.memoryFactTable.noteId,a),(0,d.eq)(j.memoryFactTable.isLatest,!0))).returning({id:j.memoryFactTable.id});return g?"ok":"missing"}),E("memory",e));return"ok"===g&&F(),g}async function A(){let[a,b]=await Promise.all([i.database.select({id:j.memoryNoteTable.id,path:j.memoryNoteTable.path,description:j.memoryNoteTable.description,aliases:j.memoryNoteTable.aliases,hits:j.memoryNoteTable.hits,lastReadAt:j.memoryNoteTable.lastReadAt,createdAt:j.memoryNoteTable.createdAt}).from(j.memoryNoteTable),i.database.select({noteId:j.memoryFactTable.noteId,count:f.sql`count(*)`}).from(j.memoryFactTable).where((0,d.eq)(j.memoryFactTable.isLatest,!0)).groupBy(j.memoryFactTable.noteId)]),c=new Map(b.map(a=>[a.noteId,a.count]));return a.filter(a=>(0,l.isAlwaysListed)(a.path)||(c.get(a.id)??0)>0).sort((a,b)=>Number((0,l.isAlwaysListed)(b.path))-Number((0,l.isAlwaysListed)(a.path))||(0,l.recallScore)(b)-(0,l.recallScore)(a)).map(a=>({path:a.path,description:a.description,aliases:a.aliases,factCount:c.get(a.id)??0,lastSeenAt:a.lastReadAt??a.createdAt}))}async function B(a){let b,c=await (b=()=>i.database.transaction(async b=>{let c=await b.delete(j.memoryFactTable).where((0,d.eq)(j.memoryFactTable.id,a)).returning({noteId:j.memoryFactTable.noteId});if(0===c.length)return null;let e=c[0].noteId,[g]=await b.select({path:j.memoryNoteTable.path,ownedByUser:j.memoryNoteTable.ownedByUser}).from(j.memoryNoteTable).where((0,d.eq)(j.memoryNoteTable.id,e)),[h]=await b.select({count:f.sql`count(*)`}).from(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.noteId,e),(0,d.eq)(j.memoryFactTable.isLatest,!0)));return h?.count!==0||!g||g.ownedByUser||(0,l.isAlwaysListed)(g.path)?(await b.update(j.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,e)),{path:g?.path??"",noteGone:!1}):(await b.delete(j.memoryNoteTable).where((0,d.eq)(j.memoryNoteTable.id,e)),{path:g.path,noteGone:!0})}),E("memory",b));return c&&F(),c}async function C(a){let[b]=await i.database.select({source:j.memoryFactTable.source,callId:j.memoryFactTable.callId}).from(j.memoryFactTable).where((0,d.eq)(j.memoryFactTable.id,a));return b??null}async function D(){let a=await i.database.delete(j.memoryNoteTable).returning({id:j.memoryNoteTable.id});return await u(),a.length>0&&F(),a.length}a.s(["addFact",0,q,"createNote",0,n,"deleteAllNotes",0,D,"deleteNote",0,p,"findFactCall",0,C,"forgetFact",0,s,"forgetFactById",0,B,"listAlwaysLoaded",0,function(){return i.database.select({id:j.memoryFactTable.id,path:j.memoryNoteTable.path,text:j.memoryFactTable.text}).from(j.memoryFactTable).innerJoin(j.memoryNoteTable,(0,d.eq)(j.memoryFactTable.noteId,j.memoryNoteTable.id)).where((0,d.and)((0,d.eq)(j.memoryFactTable.alwaysLoad,!0),(0,d.eq)(j.memoryFactTable.isLatest,!0))).orderBy((0,e.asc)(j.memoryNoteTable.path),(0,e.asc)(j.memoryFactTable.id)).limit(h.MEMORY_LIMITS.carried)},"listNoteIndex",0,A,"readNotes",0,x,"resolveNotePath",0,w,"reviseFact",0,r,"setFactAlwaysLoad",0,z,"updateNote",0,o,"writeNotes",0,y]),c()}catch(a){c(a)}},!1),661210,a=>{"use strict";var b=a.i(53112),c=a.i(706210);let d=b.z.enum(["user","call","bot"]),e=b.z.object({id:b.z.number(),text:b.z.string(),alwaysLoad:b.z.boolean(),source:d.nullish(),createdAt:c.DateLikeSchema});b.z.object({id:b.z.number(),path:b.z.string(),description:b.z.string(),aliases:b.z.string().array().nullish(),ownedByUser:b.z.boolean(),hits:b.z.number(),lastReadAt:c.DateLikeSchema.nullable(),createdAt:c.DateLikeSchema,updatedAt:c.DateLikeSchema,factCount:b.z.number(),facts:e.array()});let f=[{path:"profile",of:"The user themselves — their name, age, what they do, where they live, and whatever else says who they are"},{path:"preferences",of:"How they want things done, and said"},{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"},{path:"inbox",of:"Nowhere obvious yet"}],g="inbox",h=f.filter(a=>!a.path.endsWith("/")).map(a=>a.path),i=f.filter(a=>a.path.endsWith("/")).map(a=>a.path.slice(0,-1)),j=RegExp(`^(?:${h.join("|")}|(?:${i.join("|")})/.+)$`),k=["profile","preferences"],l=[...k,g];a.s(["APP_NAMED_NOTES",0,l,"MEMORY_ALWAYS_LISTED",0,k,"MEMORY_INBOX",0,g,"MEMORY_PATHS",0,f,"appNoteLine",0,a=>f.find(b=>b.path===a)?.of??null,"isAlwaysListed",0,a=>k.includes(a),"isAppNamed",0,a=>l.includes(a),"isMemoryPath",0,a=>j.test(a),"recallScore",0,function(a){let b=(0,c.toDate)(a.lastReadAt??a.createdAt),d=Math.max(0,(Date.now()-b.getTime())/864e5);return(a.hits+1)/(1+d)}])},138100,a=>{"use strict";var b=a.i(750227),c=a.i(569572),d=a.i(176668),e=a.i(182248),f=a.i(762805);let g=[(0,b.join)(c.APP_DIR,c.PATHS.skills.default),(0,b.join)(c.DATA_DIR,c.PATHS.skills.custom)];async function h(a,b){let c=[],g=new Set;for(let h of b){let b;try{b=await a.readdir(h,{withFileTypes:!0})}catch{continue}for(let i of b){let b,j;if(!i.isDirectory())continue;let k=`${h}/${i.name}`,l=`${k}/SKILL.md`;try{b=await a.readFile(l,"utf-8")}catch{continue}try{j=(0,f.parseFrontmatter)(b)}catch(a){d.logger.warn(`skill ${k}: SKILL.md front matter did not load — ${(0,e.errorToString)(a)}`);continue}!g.has(j.name)&&(g.add(j.name),j.disabled||c.push({name:j.name,description:j.description,path:k}))}}return c}a.s(["loadSkills",0,a=>h(a,g)])},762805,951941,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(622650),e=a.i(569572),f=a.i(53112);let g=f.z.enum(["custom","default"]),h=f.z.string().trim().min(1,"Skill name is required").max(64,"Skill name is too long").regex(/^[a-z0-9][a-z0-9_-]*$/i,"Use letters, numbers, dashes and underscores only"),i=f.z.object({name:h,description:f.z.string().trim().min(1,"Description is required"),disabled:f.z.boolean().optional()}),j=i.extend({content:f.z.string().trim().min(1,"Content is required")}),k=f.z.object({fileName:f.z.string().trim().min(1),base64:f.z.string().min(1)});a.s(["SkillDraftSchema",0,j,"SkillFrontmatterSchema",0,i,"SkillNameSchema",0,h,"SkillSourceSchema",0,g,"SkillUploadSchema",0,k],951941);var l=a.i(293480);let m={default:(0,c.resolve)(e.APP_DIR,e.PATHS.skills.default),custom:(0,c.resolve)(e.DATA_DIR,e.PATHS.skills.custom)};function n(a,b){let d=m[a],e=(0,c.resolve)(d,b),f=(0,c.relative)(d,e);return(!f||f.startsWith("..")||f.includes(c.sep)||"."===f)&&(0,l.publicError)("Skill not found"),e}function o(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]}}function p(a){let b,{head:c}=o(a);c||(0,l.publicError)("SKILL.md needs a YAML block with name and description");try{b=(0,d.parse)(c)}catch{(0,l.publicError)("SKILL.md frontmatter is not valid YAML")}let e=i.safeParse(b);return e.success||(0,l.publicError)(`SKILL.md frontmatter: ${e.error.issues[0]?.message??"invalid"}`),e.data}let q=/^disabled[ \t]*:[^\n]*(\r?\n|$)/m;async function r(a,e,f){let g,h,i=(0,c.join)(n(a,e),"SKILL.md");try{g=await (0,b.readFile)(i,"utf-8")}catch{(0,l.publicError)("Skill not found")}let{head:j,rest:k,fence:m}=o(g);j||(0,l.publicError)("This SKILL.md has no frontmatter to write to");try{h=(0,d.parse)(j)}catch{(0,l.publicError)("SKILL.md frontmatter is not valid YAML")}(!h||"object"!=typeof h||Array.isArray(h))&&(0,l.publicError)("SKILL.md frontmatter is not a YAML mapping");let p=m.includes("\r\n")?"\r\n":"\n",r=f?q.test(j)?j.replace(q,"disabled: true$1"):`${j.replace(/\s+$/,"")}${p}disabled: true`:j.replace(q,"").replace(/\s+$/,"");await (0,b.writeFile)(i,`---${p}${r}${p}---${p}${k}`)}async function s(a,d){try{let e=await (0,b.readFile)((0,c.join)(m[a],d,"SKILL.md"),"utf-8");return{...p(e),source:a,dir:d}}catch{return null}}async function t(a,d){let e=n("custom",a),f=async a=>(0,b.stat)(a).then(()=>!0,()=>!1);await f(e)&&(0,l.publicError)(`A skill named "${a}" already exists`),await f(n("default",a))&&(0,l.publicError)(`"${a}" is a built-in skill — pick another name`),await (0,b.mkdir)(e,{recursive:!0});try{for(let[a,f]of d){let d=function(a,b){let d=(0,c.resolve)(a,b);return((0,c.relative)(a,d).startsWith("..")||(0,c.resolve)(d)!==d)&&(0,l.publicError)("File not found"),d}(e,a);await (0,b.mkdir)((0,c.resolve)(d,".."),{recursive:!0}),await (0,b.writeFile)(d,f)}}catch(a){throw await (0,b.rm)(e,{recursive:!0,force:!0}),a}let g=await s("custom",a);return g||(await (0,b.rm)(e,{recursive:!0,force:!0}),(0,l.publicError)("SKILL.md could not be read back")),g}async function u(a){let c=n("custom",a);await (0,b.stat)(c).then(()=>!0,()=>!1)||(0,l.publicError)("Skill not found"),await (0,b.rm)(c,{recursive:!0,force:!0})}a.s(["deleteCustomSkill",0,u,"parseFrontmatter",0,p,"renderSkillMarkdown",0,function(a,b){return`---
|
|
151
|
+
Everything it had done is still here — answer to pick it back up.`}async function H(a,b){if(0!==d.appEventStream.watchers&&await (0,i.isAnyCallLive)())return;let c="waiting"===b.status?`${a} — needs you`:a;(0,l.desktopNotify)(c,b.outcome)}a.s(["answerTask",0,u,"cancelTask",0,v,"removeFinishedTasks",0,y,"removeTask",0,w,"startTask",0,t]),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;staticClient;lastAuthorizationUrl;constructor(a,b,c,d,e,f){this.store=a,this.serverName=b,this.oauth=c,this.callbackUrl=d,this.clientName=e,this.staticClient=f}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.staticClient??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;idleTtlMs;callbackUrl;clientName;constructor(a,b){this.store=a,this.sessions=new Map,this.connecting=new Map,this.callbackUrl=b.callbackUrl,this.idleTtlMs=b.idleTtlMs??18e5,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),/\b40[13]\b/.test(g)&&/OAuth|register/i.test(g)&&(0,k.isRemoteConfig)(f.config)&&!f.config.oauthClient?"This server does not allow automatic client registration. Register an OAuth app with the provider and add its client ID and secret.":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){let b=(0,k.isRemoteConfig)(a.config)?a.config.oauthClient:void 0;return new n(this.store,a.name,a.oauth??{},this.callbackUrl,this.clientName,b&&{client_id:b.clientId,client_secret:b.clientSecret})}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)},this.idleTtlMs);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(),oauthClient:b.z.object({clientId:b.z.string().min(1),clientSecret:b.z.string().optional()}).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),h=a.i(569572),i=a.i(184838),j=a.i(714428),k=a.i(8412),l=a.i(661210),m=b([i]);[i]=m.then?(await m)():m;let E=(0,k.createKeyedLock)(),F=()=>g.appEvents.emit({type:"memory"});async function n(a,b,c={}){let[d]=await i.database.insert(j.memoryNoteTable).values({path:a,description:b,ownedByUser:c.ownedByUser??!1}).onConflictDoNothing({target:j.memoryNoteTable.path}).returning();return d&&F(),d??null}async function o(a,b){let[c]=await i.database.update(j.memoryNoteTable).set({...b,updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,a)).returning();return c&&F(),c??null}async function p(a){let b=await i.database.delete(j.memoryNoteTable).where((0,d.eq)(j.memoryNoteTable.id,a)).returning({id:j.memoryNoteTable.id});return b.length>0&&F(),b.length>0}async function q(a,b){let[c]=await i.database.insert(j.memoryFactTable).values({noteId:a,text:b,source:"user"}).returning();return await t(a),F(),c}async function r(a,b,c){let e,f=await (e=()=>i.database.transaction(async e=>{let f=await e.update(j.memoryFactTable).set({isLatest:!1}).where((0,d.and)((0,d.eq)(j.memoryFactTable.id,b),(0,d.eq)(j.memoryFactTable.noteId,a),(0,d.eq)(j.memoryFactTable.isLatest,!0))).returning({id:j.memoryFactTable.id});if(0===f.length)return null;let[g]=await e.insert(j.memoryFactTable).values({noteId:a,text:c,source:"user"}).returning();return await e.update(j.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,a)),g}),E("memory",e));return f&&F(),f}async function s(a,b){let c=await i.database.delete(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.id,b),(0,d.eq)(j.memoryFactTable.noteId,a))).returning({id:j.memoryFactTable.id});return c.length>0&&(await t(a),F()),c.length>0}function t(a){return i.database.update(j.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,a))}async function u(){for(let a of l.MEMORY_ALWAYS_LISTED){let b=l.MEMORY_PATHS.find(b=>b.path===a)?.of??a;await i.database.insert(j.memoryNoteTable).values({path:a,description:b}).onConflictDoUpdate({target:j.memoryNoteTable.path,set:{description:b}})}}async function v(a){let b=a.map(a=>a.trim()).filter(Boolean),c=[],e=[];if(!b.length)return{found:c,missing:e};let f={id:j.memoryNoteTable.id,path:j.memoryNoteTable.path,description:j.memoryNoteTable.description},g=await i.database.select(f).from(j.memoryNoteTable).where((0,d.inArray)(j.memoryNoteTable.path,b)),h=new Map(g.map(a=>[a.path.toLowerCase(),a]));if(b.some(a=>!h.has(a.toLowerCase()))){let a=await i.database.select({...f,aliases:j.memoryNoteTable.aliases}).from(j.memoryNoteTable),b=(a,b)=>{let c=a.trim().toLowerCase();c&&!h.has(c)&&h.set(c,b)};for(let c of a)b(c.path,c);for(let c of a)for(let a of(b(c.path.slice(c.path.indexOf("/")+1),c),c.aliases??[]))b(a,c)}let k=new Set;for(let a of b){let b=h.get(a.toLowerCase());if(!b){e.push(a);continue}k.has(b.id)||(k.add(b.id),c.push(b))}return{found:c,missing:e}}async function w(a){let{found:b}=await v([a]);return b[0]?.path??null}async function x(a,b={}){let{found:c,missing:g}=await v(a);if(!c.length)return{notes:[],missing:g};let h=c.map(a=>a.id),k=await i.database.select({id:j.memoryFactTable.id,noteId:j.memoryFactTable.noteId,text:j.memoryFactTable.text,alwaysLoad:j.memoryFactTable.alwaysLoad,source:j.memoryFactTable.source,createdAt:j.memoryFactTable.createdAt,saidAt:j.callTable.startedAt}).from(j.memoryFactTable).leftJoin(j.callTable,(0,d.eq)(j.memoryFactTable.callId,j.callTable.id)).where((0,d.and)((0,d.eq)(j.memoryFactTable.isLatest,!0),(0,d.inArray)(j.memoryFactTable.noteId,h))).orderBy((0,e.asc)(j.memoryFactTable.id));return!1!==b.touch&&await i.database.update(j.memoryNoteTable).set({hits:f.sql`${j.memoryNoteTable.hits} + 1`,lastReadAt:new Date}).where((0,d.inArray)(j.memoryNoteTable.id,h)),{notes:c.map(a=>({path:a.path,description:a.description,facts:k.filter(b=>b.noteId===a.id).map(a=>({id:a.id,text:a.text,...a.saidAt?{saidAt:a.saidAt}:{}}))})),missing:g}}(0,d.inArray)(j.memoryNoteTable.path,l.MEMORY_ALWAYS_LISTED);let G=a=>a.toLowerCase().replace(/[\s.,!?…·'"`]/g,"");async function y(a,b,c=null){let e,g=[],k=[],l=[];await (e=()=>i.database.transaction(async e=>{let[i]=await e.select({count:f.sql`count(*)`}).from(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.alwaysLoad,!0),(0,d.eq)(j.memoryFactTable.isLatest,!0))),m=h.MEMORY_LIMITS.carried-Number(i?.count??0),n=(a,b)=>!!a&&(m>0?(m-=1,!0):(l.push(b),!1));for(let f of a){let a,h=f.path.trim();if(!h)continue;k.push(h);let i=f.description?.trim(),l=f.aliases?.map(a=>a.trim()).filter(Boolean),o=(f.facts??[]).map(a=>({...a,text:a.text.trim()})).filter(a=>a.text),[p]=await e.select({id:j.memoryNoteTable.id}).from(j.memoryNoteTable).where((0,d.eq)(j.memoryNoteTable.path,h));if(p)a=p.id,(i||l)&&await e.update(j.memoryNoteTable).set({...i?{description:i}:{},...l?{aliases:l}:{},updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,a));else{let[b]=await e.insert(j.memoryNoteTable).values({path:h,description:i??o[0]?.text.slice(0,80)??h,...l?{aliases:l}:{}}).returning({id:j.memoryNoteTable.id});a=b.id,i||g.push(h)}if(!o.length)continue;let q=await e.select({id:j.memoryFactTable.id,text:j.memoryFactTable.text,alwaysLoad:j.memoryFactTable.alwaysLoad}).from(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.noteId,a),(0,d.eq)(j.memoryFactTable.isLatest,!0))),r=new Map(q.map(a=>[G(a.text),a])),s=async(a,b,c)=>{if(b===a.alwaysLoad)return;let f=b?n(!0,c):(m+=1,!1);f!==a.alwaysLoad&&(await e.update(j.memoryFactTable).set({alwaysLoad:f}).where((0,d.eq)(j.memoryFactTable.id,a.id)),a.alwaysLoad=f)};for(let f of o){if(null!=f.replaces){let[g]=await e.select({id:j.memoryFactTable.id,text:j.memoryFactTable.text,alwaysLoad:j.memoryFactTable.alwaysLoad}).from(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.id,f.replaces),(0,d.eq)(j.memoryFactTable.noteId,a),(0,d.eq)(j.memoryFactTable.isLatest,!0)));if(g){if(G(g.text)===G(f.text)){await s(g,f.alwaysLoad??g.alwaysLoad,f.text),r.set(G(g.text),g);continue}await e.update(j.memoryFactTable).set({isLatest:!1}).where((0,d.eq)(j.memoryFactTable.id,g.id)),r.delete(G(g.text)),g.alwaysLoad&&(m+=1);let[h]=await e.insert(j.memoryFactTable).values({noteId:a,text:f.text,source:b,callId:c,alwaysLoad:n(f.alwaysLoad??g.alwaysLoad,f.text)}).returning({id:j.memoryFactTable.id,alwaysLoad:j.memoryFactTable.alwaysLoad});r.set(G(f.text),{...h,text:f.text});continue}}let g=r.get(G(f.text));if(g){null!=f.alwaysLoad&&await s(g,f.alwaysLoad,f.text);continue}let[h]=await e.insert(j.memoryFactTable).values({noteId:a,text:f.text,source:b,callId:c,alwaysLoad:n(!0===f.alwaysLoad,f.text)}).returning({id:j.memoryFactTable.id,alwaysLoad:j.memoryFactTable.alwaysLoad});r.set(G(f.text),{...h,text:f.text})}await e.update(j.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,a))}}),E("memory",e));let{notes:m}=await x(k,{touch:!1});return F(),{notes:m,unnamed:g,notLoaded:l}}async function z(a,b,c){let e,g=await (e=()=>i.database.transaction(async e=>{if(c){let[a]=await e.select({count:f.sql`count(*)`}).from(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.alwaysLoad,!0),(0,d.eq)(j.memoryFactTable.isLatest,!0)));if(Number(a?.count??0)>=h.MEMORY_LIMITS.carried)return"full"}let[g]=await e.update(j.memoryFactTable).set({alwaysLoad:c}).where((0,d.and)((0,d.eq)(j.memoryFactTable.id,b),(0,d.eq)(j.memoryFactTable.noteId,a),(0,d.eq)(j.memoryFactTable.isLatest,!0))).returning({id:j.memoryFactTable.id});return g?"ok":"missing"}),E("memory",e));return"ok"===g&&F(),g}async function A(){let[a,b]=await Promise.all([i.database.select({id:j.memoryNoteTable.id,path:j.memoryNoteTable.path,description:j.memoryNoteTable.description,aliases:j.memoryNoteTable.aliases,hits:j.memoryNoteTable.hits,lastReadAt:j.memoryNoteTable.lastReadAt,createdAt:j.memoryNoteTable.createdAt}).from(j.memoryNoteTable),i.database.select({noteId:j.memoryFactTable.noteId,count:f.sql`count(*)`}).from(j.memoryFactTable).where((0,d.eq)(j.memoryFactTable.isLatest,!0)).groupBy(j.memoryFactTable.noteId)]),c=new Map(b.map(a=>[a.noteId,a.count]));return a.filter(a=>(0,l.isAlwaysListed)(a.path)||(c.get(a.id)??0)>0).sort((a,b)=>Number((0,l.isAlwaysListed)(b.path))-Number((0,l.isAlwaysListed)(a.path))||(0,l.recallScore)(b)-(0,l.recallScore)(a)).map(a=>({path:a.path,description:a.description,aliases:a.aliases,factCount:c.get(a.id)??0,lastSeenAt:a.lastReadAt??a.createdAt}))}async function B(a){let b,c=await (b=()=>i.database.transaction(async b=>{let c=await b.delete(j.memoryFactTable).where((0,d.eq)(j.memoryFactTable.id,a)).returning({noteId:j.memoryFactTable.noteId});if(0===c.length)return null;let e=c[0].noteId,[g]=await b.select({path:j.memoryNoteTable.path,ownedByUser:j.memoryNoteTable.ownedByUser}).from(j.memoryNoteTable).where((0,d.eq)(j.memoryNoteTable.id,e)),[h]=await b.select({count:f.sql`count(*)`}).from(j.memoryFactTable).where((0,d.and)((0,d.eq)(j.memoryFactTable.noteId,e),(0,d.eq)(j.memoryFactTable.isLatest,!0)));return h?.count!==0||!g||g.ownedByUser||(0,l.isAlwaysListed)(g.path)?(await b.update(j.memoryNoteTable).set({updatedAt:new Date}).where((0,d.eq)(j.memoryNoteTable.id,e)),{path:g?.path??"",noteGone:!1}):(await b.delete(j.memoryNoteTable).where((0,d.eq)(j.memoryNoteTable.id,e)),{path:g.path,noteGone:!0})}),E("memory",b));return c&&F(),c}async function C(a){let[b]=await i.database.select({source:j.memoryFactTable.source,callId:j.memoryFactTable.callId}).from(j.memoryFactTable).where((0,d.eq)(j.memoryFactTable.id,a));return b??null}async function D(){let a=await i.database.delete(j.memoryNoteTable).returning({id:j.memoryNoteTable.id});return await u(),a.length>0&&F(),a.length}a.s(["addFact",0,q,"createNote",0,n,"deleteAllNotes",0,D,"deleteNote",0,p,"findFactCall",0,C,"forgetFact",0,s,"forgetFactById",0,B,"listAlwaysLoaded",0,function(){return i.database.select({id:j.memoryFactTable.id,path:j.memoryNoteTable.path,text:j.memoryFactTable.text}).from(j.memoryFactTable).innerJoin(j.memoryNoteTable,(0,d.eq)(j.memoryFactTable.noteId,j.memoryNoteTable.id)).where((0,d.and)((0,d.eq)(j.memoryFactTable.alwaysLoad,!0),(0,d.eq)(j.memoryFactTable.isLatest,!0))).orderBy((0,e.asc)(j.memoryNoteTable.path),(0,e.asc)(j.memoryFactTable.id)).limit(h.MEMORY_LIMITS.carried)},"listNoteIndex",0,A,"readNotes",0,x,"resolveNotePath",0,w,"reviseFact",0,r,"setFactAlwaysLoad",0,z,"updateNote",0,o,"writeNotes",0,y]),c()}catch(a){c(a)}},!1),661210,a=>{"use strict";var b=a.i(53112),c=a.i(706210);let d=b.z.enum(["user","call","bot"]),e=b.z.object({id:b.z.number(),text:b.z.string(),alwaysLoad:b.z.boolean(),source:d.nullish(),createdAt:c.DateLikeSchema});b.z.object({id:b.z.number(),path:b.z.string(),description:b.z.string(),aliases:b.z.string().array().nullish(),ownedByUser:b.z.boolean(),hits:b.z.number(),lastReadAt:c.DateLikeSchema.nullable(),createdAt:c.DateLikeSchema,updatedAt:c.DateLikeSchema,factCount:b.z.number(),facts:e.array()});let f=[{path:"profile",of:"The user themselves — their name, age, what they do, where they live, and whatever else says who they are"},{path:"preferences",of:"How they want things done, and said"},{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"},{path:"inbox",of:"Nowhere obvious yet"}],g="inbox",h=f.filter(a=>!a.path.endsWith("/")).map(a=>a.path),i=f.filter(a=>a.path.endsWith("/")).map(a=>a.path.slice(0,-1)),j=RegExp(`^(?:${h.join("|")}|(?:${i.join("|")})/.+)$`),k=["profile","preferences"],l=[...k,g];a.s(["APP_NAMED_NOTES",0,l,"MEMORY_ALWAYS_LISTED",0,k,"MEMORY_INBOX",0,g,"MEMORY_PATHS",0,f,"appNoteLine",0,a=>f.find(b=>b.path===a)?.of??null,"isAlwaysListed",0,a=>k.includes(a),"isAppNamed",0,a=>l.includes(a),"isMemoryPath",0,a=>j.test(a),"recallScore",0,function(a){let b=(0,c.toDate)(a.lastReadAt??a.createdAt),d=Math.max(0,(Date.now()-b.getTime())/864e5);return(a.hits+1)/(1+d)}])},138100,a=>{"use strict";var b=a.i(750227),c=a.i(569572),d=a.i(176668),e=a.i(182248),f=a.i(762805);let g=[(0,b.join)(c.APP_DIR,c.PATHS.skills.default),(0,b.join)(c.DATA_DIR,c.PATHS.skills.custom)];async function h(a,b){let c=[],g=new Set;for(let h of b){let b;try{b=await a.readdir(h,{withFileTypes:!0})}catch{continue}for(let i of b){let b,j;if(!i.isDirectory())continue;let k=`${h}/${i.name}`,l=`${k}/SKILL.md`;try{b=await a.readFile(l,"utf-8")}catch{continue}try{j=(0,f.parseFrontmatter)(b)}catch(a){d.logger.warn(`skill ${k}: SKILL.md front matter did not load — ${(0,e.errorToString)(a)}`);continue}!g.has(j.name)&&(g.add(j.name),j.disabled||c.push({name:j.name,description:j.description,path:k}))}}return c}a.s(["loadSkills",0,a=>h(a,g)])},762805,951941,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(622650),e=a.i(569572),f=a.i(53112);let g=f.z.enum(["custom","default"]),h=f.z.string().trim().min(1,"Skill name is required").max(64,"Skill name is too long").regex(/^[a-z0-9][a-z0-9_-]*$/i,"Use letters, numbers, dashes and underscores only"),i=f.z.object({name:h,description:f.z.string().trim().min(1,"Description is required"),disabled:f.z.boolean().optional()}),j=i.extend({content:f.z.string().trim().min(1,"Content is required")}),k=f.z.object({fileName:f.z.string().trim().min(1),base64:f.z.string().min(1)});a.s(["SkillDraftSchema",0,j,"SkillFrontmatterSchema",0,i,"SkillNameSchema",0,h,"SkillSourceSchema",0,g,"SkillUploadSchema",0,k],951941);var l=a.i(293480);let m={default:(0,c.resolve)(e.APP_DIR,e.PATHS.skills.default),custom:(0,c.resolve)(e.DATA_DIR,e.PATHS.skills.custom)};function n(a,b){let d=m[a],e=(0,c.resolve)(d,b),f=(0,c.relative)(d,e);return(!f||f.startsWith("..")||f.includes(c.sep)||"."===f)&&(0,l.publicError)("Skill not found"),e}function o(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]}}function p(a){let b,{head:c}=o(a);c||(0,l.publicError)("SKILL.md needs a YAML block with name and description");try{b=(0,d.parse)(c)}catch{(0,l.publicError)("SKILL.md frontmatter is not valid YAML")}let e=i.safeParse(b);return e.success||(0,l.publicError)(`SKILL.md frontmatter: ${e.error.issues[0]?.message??"invalid"}`),e.data}let q=/^disabled[ \t]*:[^\n]*(\r?\n|$)/m;async function r(a,e,f){let g,h,i=(0,c.join)(n(a,e),"SKILL.md");try{g=await (0,b.readFile)(i,"utf-8")}catch{(0,l.publicError)("Skill not found")}let{head:j,rest:k,fence:m}=o(g);j||(0,l.publicError)("This SKILL.md has no frontmatter to write to");try{h=(0,d.parse)(j)}catch{(0,l.publicError)("SKILL.md frontmatter is not valid YAML")}(!h||"object"!=typeof h||Array.isArray(h))&&(0,l.publicError)("SKILL.md frontmatter is not a YAML mapping");let p=m.includes("\r\n")?"\r\n":"\n",r=f?q.test(j)?j.replace(q,"disabled: true$1"):`${j.replace(/\s+$/,"")}${p}disabled: true`:j.replace(q,"").replace(/\s+$/,"");await (0,b.writeFile)(i,`---${p}${r}${p}---${p}${k}`)}async function s(a,d){try{let e=await (0,b.readFile)((0,c.join)(m[a],d,"SKILL.md"),"utf-8");return{...p(e),source:a,dir:d}}catch{return null}}async function t(a,d){let e=n("custom",a),f=async a=>(0,b.stat)(a).then(()=>!0,()=>!1);await f(e)&&(0,l.publicError)(`A skill named "${a}" already exists`),await f(n("default",a))&&(0,l.publicError)(`"${a}" is a built-in skill — pick another name`),await (0,b.mkdir)(e,{recursive:!0});try{for(let[a,f]of d){let d=function(a,b){let d=(0,c.resolve)(a,b);return((0,c.relative)(a,d).startsWith("..")||(0,c.resolve)(d)!==d)&&(0,l.publicError)("File not found"),d}(e,a);await (0,b.mkdir)((0,c.resolve)(d,".."),{recursive:!0}),await (0,b.writeFile)(d,f)}}catch(a){throw await (0,b.rm)(e,{recursive:!0,force:!0}),a}let g=await s("custom",a);return g||(await (0,b.rm)(e,{recursive:!0,force:!0}),(0,l.publicError)("SKILL.md could not be read back")),g}async function u(a){let c=n("custom",a);await (0,b.stat)(c).then(()=>!0,()=>!1)||(0,l.publicError)("Skill not found"),await (0,b.rm)(c,{recursive:!0,force:!0})}a.s(["deleteCustomSkill",0,u,"parseFrontmatter",0,p,"renderSkillMarkdown",0,function(a,b){return`---
|
|
142
152
|
${(0,d.stringify)(a).trim()}
|
|
143
153
|
---
|
|
144
154
|
|
|
@@ -238,4 +248,4 @@ ${b}`:c}else{let a=e.commentBefore;e.commentBefore=a?`${c}
|
|
|
238
248
|
${a}`:c}}if(b){for(let b=0;b<this.errors.length;++b)a.errors.push(this.errors[b]);for(let b=0;b<this.warnings.length;++b)a.warnings.push(this.warnings[b])}else a.errors=this.errors,a.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:l(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(a,b=!1,c=-1){for(let b of a)yield*this.next(b);yield*this.end(b,c)}*next(a){switch(d.env.LOG_STREAM&&console.dir(a,{depth:null}),a.type){case"directive":this.directives.add(a.source,(b,c,d)=>{let e=k(a);e[0]+=b,this.onError(e,"BAD_DIRECTIVE",c,d)}),this.prelude.push(a.source),this.atDirectives=!0;break;case"document":{let b=i.composeDoc(this.options,this.directives,a,this.onError);this.atDirectives&&!b.directives.docStart&&this.onError(a,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(b,!1),this.doc&&(yield this.doc),this.doc=b,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(a.source);break;case"error":{let b=a.source?`${a.message}: ${JSON.stringify(a.source)}`:a.message,c=new g.YAMLParseError(k(a),"UNEXPECTED_TOKEN",b);this.atDirectives||!this.doc?this.errors.push(c):this.doc.errors.push(c);break}case"doc-end":{if(!this.doc){this.errors.push(new g.YAMLParseError(k(a),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let b=j.resolveEnd(a.end,a.offset+a.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),b.comment){let a=this.doc.comment;this.doc.comment=a?`${a}
|
|
239
249
|
${b.comment}`:b.comment}this.doc.range[2]=b.offset;break}default:this.errors.push(new g.YAMLParseError(k(a),"UNEXPECTED_TOKEN",`Unsupported token ${a.type}`))}}*end(a=!1,b=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(a){let a=Object.assign({_directives:this.directives},this.options),c=new f.Document(void 0,a);this.atDirectives&&this.onError(b,"MISSING_CHAR","Missing directives-end indicator line"),c.range=[0,b,b],this.decorate(c,!1),yield c}}}},286888,(a,b,c)=>{"use strict";var d=a.r(871014),e=a.r(121525),f=a.r(725717),g=a.r(688583);function h(a,b){if(b)for(let c of b)switch(c.type){case"space":case"comment":a.push(c);break;case"newline":return a.push(c),!0}return!1}function i(a,b,c){switch(a.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":a.type=c,a.source=b;break;case"block-scalar":{let d=a.props.slice(1),e=b.length;for(let b of("block-scalar-header"===a.props[0].type&&(e-=a.props[0].source.length),d))b.offset+=e;delete a.props,Object.assign(a,{type:c,source:b,end:d});break}case"block-map":case"block-seq":{let d={type:"newline",offset:a.offset+b.length,indent:a.indent,source:"\n"};delete a.items,Object.assign(a,{type:c,source:b,end:[d]});break}default:{let d="indent"in a?a.indent:-1,e="end"in a&&Array.isArray(a.end)?a.end.filter(a=>"space"===a.type||"comment"===a.type||"newline"===a.type):[];for(let b of Object.keys(a))"type"!==b&&"offset"!==b&&delete a[b];Object.assign(a,{type:c,indent:d,source:b,end:e})}}}c.createScalarToken=function(a,b){let{implicitKey:c=!1,indent:d,inFlow:e=!1,offset:f=-1,type:i="PLAIN"}=b,j=g.stringifyString({type:i,value:a},{implicitKey:c,indent:d>0?" ".repeat(d):"",inFlow:e,options:{blockQuote:!0,lineWidth:-1}}),k=b.end??[{type:"newline",offset:-1,indent:d,source:"\n"}];switch(j[0]){case"|":case">":{let a=j.indexOf("\n"),b=j.substring(0,a),c=j.substring(a+1)+"\n",e=[{type:"block-scalar-header",offset:f,indent:d,source:b}];return h(e,k)||e.push({type:"newline",offset:-1,indent:d,source:"\n"}),{type:"block-scalar",offset:f,indent:d,props:e,source:c}}case'"':return{type:"double-quoted-scalar",offset:f,indent:d,source:j,end:k};case"'":return{type:"single-quoted-scalar",offset:f,indent:d,source:j,end:k};default:return{type:"scalar",offset:f,indent:d,source:j,end:k}}},c.resolveAsScalar=function(a,b=!0,c){if(a){let g=(a,b,d)=>{let e="number"==typeof a?a:Array.isArray(a)?a[0]:a.offset;if(c)c(e,b,d);else throw new f.YAMLParseError([e,e+1],b,d)};switch(a.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return e.resolveFlowScalar(a,b,g);case"block-scalar":return d.resolveBlockScalar({options:{strict:b}},a,g)}}return null},c.setScalarValue=function(a,b,c={}){let{afterKey:d=!1,implicitKey:e=!1,inFlow:f=!1,type:j}=c,k="indent"in a?a.indent:null;if(d&&"number"==typeof k&&(k+=2),!j)switch(a.type){case"single-quoted-scalar":j="QUOTE_SINGLE";break;case"double-quoted-scalar":j="QUOTE_DOUBLE";break;case"block-scalar":{let b=a.props[0];if("block-scalar-header"!==b.type)throw Error("Invalid block scalar header");j=">"===b.source[0]?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:j="PLAIN"}let l=g.stringifyString({type:j,value:b},{implicitKey:e||null===k,indent:null!==k&&k>0?" ".repeat(k):"",inFlow:f,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":!function(a,b){let c=b.indexOf("\n"),d=b.substring(0,c),e=b.substring(c+1)+"\n";if("block-scalar"===a.type){let b=a.props[0];if("block-scalar-header"!==b.type)throw Error("Invalid block scalar header");b.source=d,a.source=e}else{let{offset:b}=a,c="indent"in a?a.indent:-1,f=[{type:"block-scalar-header",offset:b,indent:c,source:d}];for(let b of(h(f,"end"in a?a.end:void 0)||f.push({type:"newline",offset:-1,indent:c,source:"\n"}),Object.keys(a)))"type"!==b&&"offset"!==b&&delete a[b];Object.assign(a,{type:"block-scalar",indent:c,props:f,source:e})}}(a,l);break;case'"':i(a,l,"double-quoted-scalar");break;case"'":i(a,l,"single-quoted-scalar");break;default:i(a,l,"scalar")}}},825449,(a,b,c)=>{"use strict";function d(a){switch(a.type){case"block-scalar":{let b="";for(let c of a.props)b+=d(c);return b+a.source}case"block-map":case"block-seq":{let b="";for(let c of a.items)b+=e(c);return b}case"flow-collection":{let b=a.start.source;for(let c of a.items)b+=e(c);for(let c of a.end)b+=c.source;return b}case"document":{let b=e(a);if(a.end)for(let c of a.end)b+=c.source;return b}default:{let b=a.source;if("end"in a&&a.end)for(let c of a.end)b+=c.source;return b}}}function e({start:a,key:b,sep:c,value:f}){let g="";for(let b of a)g+=b.source;if(b&&(g+=d(b)),c)for(let a of c)g+=a.source;return f&&(g+=d(f)),g}c.stringify=a=>"type"in a?d(a):e(a)},402135,(a,b,c)=>{"use strict";let d=Symbol("break visit"),e=Symbol("skip children"),f=Symbol("remove item");function g(a,b){"type"in a&&"document"===a.type&&(a={start:a.start,value:a.value}),function a(b,c,e){let g=e(c,b);if("symbol"==typeof g)return g;for(let h of["key","value"]){let i=c[h];if(i&&"items"in i){for(let c=0;c<i.items.length;++c){let g=a(Object.freeze(b.concat([[h,c]])),i.items[c],e);if("number"==typeof g)c=g-1;else{if(g===d)return d;g===f&&(i.items.splice(c,1),c-=1)}}"function"==typeof g&&"key"===h&&(g=g(c,b))}}return"function"==typeof g?g(c,b):g}(Object.freeze([]),a,b)}g.BREAK=d,g.SKIP=e,g.REMOVE=f,g.itemAtPath=(a,b)=>{let c=a;for(let[a,d]of b){let b=c?.[a];if(!b||!("items"in b))return;c=b.items[d]}return c},g.parentCollection=(a,b)=>{let c=g.itemAtPath(a,b.slice(0,-1)),d=b[b.length-1][0],e=c?.[d];if(e&&"items"in e)return e;throw Error("Parent collection not found")},c.visit=g},2704,(a,b,c)=>{"use strict";var d=a.r(286888),e=a.r(825449),f=a.r(402135);c.createScalarToken=d.createScalarToken,c.resolveAsScalar=d.resolveAsScalar,c.setScalarValue=d.setScalarValue,c.stringify=e.stringify,c.visit=f.visit,c.BOM="\uFEFF",c.DOCUMENT="\x02",c.FLOW_END="\x18",c.SCALAR="\x1f",c.isCollection=a=>!!a&&"items"in a,c.isScalar=a=>!!a&&("scalar"===a.type||"single-quoted-scalar"===a.type||"double-quoted-scalar"===a.type||"block-scalar"===a.type),c.prettyToken=function(a){switch(a){case"\uFEFF":return"<BOM>";case"\x02":return"<DOC>";case"\x18":return"<FLOW_END>";case"\x1f":return"<SCALAR>";default:return JSON.stringify(a)}},c.tokenType=function(a){switch(a){case"\uFEFF":return"byte-order-mark";case"\x02":return"doc-mode";case"\x18":return"flow-error-end";case"\x1f":return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(a[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}},66326,(a,b,c)=>{"use strict";var d=a.r(2704);function e(a){switch(a){case void 0:case" ":case"\n":case"\r":case" ":return!0;default:return!1}}let f=new Set("0123456789ABCDEFabcdef"),g=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),h=new Set(",[]{}"),i=new Set(" ,[]{}\n\r "),j=a=>!a||i.has(a);c.Lexer=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(a,b=!1){if(a){if("string"!=typeof a)throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+a:a,this.lineEndPos=null}this.atEnd=!b;let c=this.next??"stream";for(;c&&(b||this.hasChars(1));)c=yield*this.parseNext(c)}atLineEnd(){let a=this.pos,b=this.buffer[a];for(;" "===b||" "===b;)b=this.buffer[++a];return!b||"#"===b||"\n"===b||"\r"===b&&"\n"===this.buffer[a+1]}charAt(a){return this.buffer[this.pos+a]}continueScalar(a){let b=this.buffer[a];if(this.indentNext>0){let c=0;for(;" "===b;)b=this.buffer[++c+a];if("\r"===b){let b=this.buffer[c+a+1];if("\n"===b||!b&&!this.atEnd)return a+c+1}return"\n"!==b&&!(c>=this.indentNext)&&(b||this.atEnd)?-1:a+c}if("-"===b||"."===b){let b=this.buffer.substr(a,3);if(("---"===b||"..."===b)&&e(this.buffer[a+3]))return -1}return a}getLine(){let a=this.lineEndPos;return(("number"!=typeof a||-1!==a&&a<this.pos)&&(a=this.buffer.indexOf("\n",this.pos),this.lineEndPos=a),-1===a)?this.atEnd?this.buffer.substring(this.pos):null:("\r"===this.buffer[a-1]&&(a-=1),this.buffer.substring(this.pos,a))}hasChars(a){return this.pos+a<=this.buffer.length}setNext(a){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=a,null}peek(a){return this.buffer.substr(this.pos,a)}*parseNext(a){switch(a){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let a=this.getLine();if(null===a)return this.setNext("stream");if(a[0]===d.BOM&&(yield*this.pushCount(1),a=a.substring(1)),"%"===a[0]){let b=a.length,c=a.indexOf("#");for(;-1!==c;){let d=a[c-1];if(" "===d||" "===d){b=c-1;break}c=a.indexOf("#",c+1)}for(;;){let c=a[b-1];if(" "===c||" "===c)b-=1;else break}let d=(yield*this.pushCount(b))+(yield*this.pushSpaces(!0));return yield*this.pushCount(a.length-d),this.pushNewline(),"stream"}if(this.atLineEnd()){let b=yield*this.pushSpaces(!0);return yield*this.pushCount(a.length-b),yield*this.pushNewline(),"stream"}return yield d.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let a=this.charAt(0);if(!a&&!this.atEnd)return this.setNext("line-start");if("-"===a||"."===a){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let a=this.peek(3);if(("---"===a||"..."===a)&&e(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"---"===a?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!e(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[a,b]=this.peek(2);if(!b&&!this.atEnd)return this.setNext("block-start");if(("-"===a||"?"===a||":"===a)&&e(b)){let a=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=a,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let a=this.getLine();if(null===a)return this.setNext("doc");let b=yield*this.pushIndicators();switch(a[b]){case"#":yield*this.pushCount(a.length-b);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(j),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return b+=yield*this.parseBlockScalarHeader(),b+=yield*this.pushSpaces(!0),yield*this.pushCount(a.length-b),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let a,b,c=-1;do(a=yield*this.pushNewline())>0?(b=yield*this.pushSpaces(!1),this.indentValue=c=b):b=0,b+=yield*this.pushSpaces(!0);while(a+b>0)let f=this.getLine();if(null===f)return this.setNext("flow");if((-1!==c&&c<this.indentNext&&"#"!==f[0]||0===c&&(f.startsWith("---")||f.startsWith("..."))&&e(f[3]))&&(c!==this.indentNext-1||1!==this.flowLevel||"]"!==f[0]&&"}"!==f[0]))return this.flowLevel=0,yield d.FLOW_END,yield*this.parseLineStart();let g=0;for(;","===f[g];)g+=yield*this.pushCount(1),g+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(f[g+=yield*this.pushIndicators()]){case void 0:return"flow";case"#":return yield*this.pushCount(f.length-g),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(j),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let a=this.charAt(1);if(this.flowKey||e(a)||","===a)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let a=this.charAt(0),b=this.buffer.indexOf(a,this.pos+1);if("'"===a)for(;-1!==b&&"'"===this.buffer[b+1];)b=this.buffer.indexOf("'",b+2);else for(;-1!==b;){let a=0;for(;"\\"===this.buffer[b-1-a];)a+=1;if(a%2==0)break;b=this.buffer.indexOf('"',b+1)}let c=this.buffer.substring(0,b),d=c.indexOf("\n",this.pos);if(-1!==d){for(;-1!==d;){let a=this.continueScalar(d+1);if(-1===a)break;d=c.indexOf("\n",a)}-1!==d&&(b=d-("\r"===c[d-1]?2:1))}if(-1===b){if(!this.atEnd)return this.setNext("quoted-scalar");b=this.buffer.length}return yield*this.pushToIndex(b+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let a=this.pos;for(;;){let b=this.buffer[++a];if("+"===b)this.blockScalarKeep=!0;else if(b>"0"&&b<="9")this.blockScalarIndent=Number(b)-1;else if("-"!==b)break}return yield*this.pushUntil(a=>e(a)||"#"===a)}*parseBlockScalar(){let a,b=this.pos-1,c=0;b:for(let d=this.pos;a=this.buffer[d];++d)switch(a){case" ":c+=1;break;case"\n":b=d,c=0;break;case"\r":{let a=this.buffer[d+1];if(!a&&!this.atEnd)return this.setNext("block-scalar");if("\n"===a)break}default:break b}if(!a&&!this.atEnd)return this.setNext("block-scalar");if(c>=this.indentNext){-1===this.blockScalarIndent?this.indentNext=c:this.indentNext=this.blockScalarIndent+(0===this.indentNext?1:this.indentNext);do{let a=this.continueScalar(b+1);if(-1===a)break;b=this.buffer.indexOf("\n",a)}while(-1!==b)if(-1===b){if(!this.atEnd)return this.setNext("block-scalar");b=this.buffer.length}}let e=b+1;for(a=this.buffer[e];" "===a;)a=this.buffer[++e];if(" "===a){for(;" "===a||" "===a||"\r"===a||"\n"===a;)a=this.buffer[++e];b=e-1}else if(!this.blockScalarKeep)for(;;){let a=b-1,d=this.buffer[a];"\r"===d&&(d=this.buffer[--a]);let e=a;for(;" "===d;)d=this.buffer[--a];if("\n"===d&&a>=this.pos&&a+1+c>e)b=a;else break}return yield d.SCALAR,yield*this.pushToIndex(b+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let a,b=this.flowLevel>0,c=this.pos-1,f=this.pos-1;for(;a=this.buffer[++f];)if(":"===a){let a=this.buffer[f+1];if(e(a)||b&&h.has(a))break;c=f}else if(e(a)){let d=this.buffer[f+1];if("\r"===a&&("\n"===d?(f+=1,a="\n",d=this.buffer[f+1]):c=f),"#"===d||b&&h.has(d))break;if("\n"===a){let a=this.continueScalar(f+1);if(-1===a)break;f=Math.max(f,a-2)}}else{if(b&&h.has(a))break;c=f}return a||this.atEnd?(yield d.SCALAR,yield*this.pushToIndex(c+1,!0),b?"flow":"doc"):this.setNext("plain-scalar")}*pushCount(a){return a>0?(yield this.buffer.substr(this.pos,a),this.pos+=a,a):0}*pushToIndex(a,b){let c=this.buffer.slice(this.pos,a);return c?(yield c,this.pos+=c.length,c.length):(b&&(yield""),0)}*pushIndicators(){let a=0;for(;;){switch(this.charAt(0)){case"!":a+=yield*this.pushTag(),a+=yield*this.pushSpaces(!0);continue;case"&":a+=yield*this.pushUntil(j),a+=yield*this.pushSpaces(!0);continue;case"-":case"?":case":":{let b=this.flowLevel>0,c=this.charAt(1);if(e(c)||b&&h.has(c)){b?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0);continue}}}break}return a}*pushTag(){if("<"===this.charAt(1)){let a=this.pos+2,b=this.buffer[a];for(;!e(b)&&">"!==b;)b=this.buffer[++a];return yield*this.pushToIndex(">"===b?a+1:a,!1)}{let a=this.pos+1,b=this.buffer[a];for(;b;)if(g.has(b))b=this.buffer[++a];else if("%"===b&&f.has(this.buffer[a+1])&&f.has(this.buffer[a+2]))b=this.buffer[a+=3];else break;return yield*this.pushToIndex(a,!1)}}*pushNewline(){let a=this.buffer[this.pos];return"\n"===a?yield*this.pushCount(1):"\r"===a&&"\n"===this.charAt(1)?yield*this.pushCount(2):0}*pushSpaces(a){let b,c=this.pos-1;do b=this.buffer[++c];while(" "===b||a&&" "===b)let d=c-this.pos;return d>0&&(yield this.buffer.substr(this.pos,d),this.pos=c),d}*pushUntil(a){let b=this.pos,c=this.buffer[b];for(;!a(c);)c=this.buffer[++b];return yield*this.pushToIndex(b,!1)}}},746987,(a,b,c)=>{"use strict";c.LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=a=>this.lineStarts.push(a),this.linePos=a=>{let b=0,c=this.lineStarts.length;for(;b<c;){let d=b+c>>1;this.lineStarts[d]<a?b=d+1:c=d}if(this.lineStarts[b]===a)return{line:b+1,col:1};if(0===b)return{line:0,col:a};let d=this.lineStarts[b-1];return{line:b,col:a-d+1}}}}},309575,(a,b,c)=>{"use strict";var d=a.r(605365),e=a.r(2704),f=a.r(66326);function g(a,b){for(let c=0;c<a.length;++c)if(a[c].type===b)return!0;return!1}function h(a){for(let b=0;b<a.length;++b)switch(a[b].type){case"space":case"comment":case"newline":break;default:return b}return -1}function i(a){switch(a?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function j(a){switch(a.type){case"document":return a.start;case"block-map":{let b=a.items[a.items.length-1];return b.sep??b.start}case"block-seq":return a.items[a.items.length-1].start;default:return[]}}function k(a){if(0===a.length)return[];let b=a.length;b:for(;--b>=0;)switch(a[b].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break b}for(;a[++b]?.type==="space";);return a.splice(b,a.length)}function l(a,b){if(b.length<1e5)Array.prototype.push.apply(a,b);else for(let c=0;c<b.length;++c)a.push(b[c])}function m(a){if("flow-seq-start"===a.start.type)for(let b of a.items)!b.sep||b.value||g(b.start,"explicit-key-ind")||g(b.sep,"map-value-ind")||(b.key&&(b.value=b.key),delete b.key,i(b.value)?b.value.end?l(b.value.end,b.sep):b.value.end=b.sep:l(b.start,b.sep),delete b.sep)}c.Parser=class{constructor(a){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new f.Lexer,this.onNewLine=a}*parse(a,b=!1){for(let c of(this.onNewLine&&0===this.offset&&this.onNewLine(0),this.lexer.lex(a,b)))yield*this.next(c);b||(yield*this.end())}*next(a){if(this.source=a,d.env.LOG_TOKENS&&console.log("|",e.prettyToken(a)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=a.length;return}let b=e.tokenType(a);if(b)if("scalar"===b)this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=b,yield*this.step(),b){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+a.length);break;case"space":this.atNewLine&&" "===a[0]&&(this.indent+=a.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=a.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=a.length}else{let b=`Not a YAML token: ${a}`;yield*this.pop({type:"error",offset:this.offset,message:b,source:a}),this.offset+=a.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let a=this.peek(1);if("doc-end"===this.type&&a?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!a)return yield*this.stream();switch(a.type){case"document":return yield*this.document(a);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(a);case"block-scalar":return yield*this.blockScalar(a);case"block-map":return yield*this.blockMap(a);case"block-seq":return yield*this.blockSequence(a);case"flow-collection":return yield*this.flowCollection(a);case"doc-end":return yield*this.documentEnd(a)}yield*this.pop()}peek(a){return this.stack[this.stack.length-a]}*pop(a){let b=a??this.stack.pop();if(b)if(0===this.stack.length)yield b;else{let a=this.peek(1);switch("block-scalar"===b.type?b.indent="indent"in a?a.indent:0:"flow-collection"===b.type&&"document"===a.type&&(b.indent=0),"flow-collection"===b.type&&m(b),a.type){case"document":a.value=b;break;case"block-scalar":a.props.push(b);break;case"block-map":{let c=a.items[a.items.length-1];if(c.value){a.items.push({start:[],key:b,sep:[]}),this.onKeyLine=!0;return}if(c.sep)c.value=b;else{Object.assign(c,{key:b,sep:[]}),this.onKeyLine=!c.explicitKey;return}break}case"block-seq":{let c=a.items[a.items.length-1];c.value?a.items.push({start:[],value:b}):c.value=b;break}case"flow-collection":{let c=a.items[a.items.length-1];!c||c.value?a.items.push({start:[],key:b,sep:[]}):c.sep?c.value=b:Object.assign(c,{key:b,sep:[]});return}default:yield*this.pop(),yield*this.pop(b)}if(("document"===a.type||"block-map"===a.type||"block-seq"===a.type)&&("block-map"===b.type||"block-seq"===b.type)){let c=b.items[b.items.length-1];c&&!c.sep&&!c.value&&c.start.length>0&&-1===h(c.start)&&(0===b.indent||c.start.every(a=>"comment"!==a.type||a.indent<b.indent))&&("document"===a.type?a.end=c.start:a.items.push({start:c.start}),b.items.splice(-1,1))}}else yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let a={type:"document",offset:this.offset,start:[]};"doc-start"===this.type&&a.start.push(this.sourceToken),this.stack.push(a);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(a){if(a.value)return yield*this.lineEnd(a);switch(this.type){case"doc-start":-1!==h(a.start)?(yield*this.pop(),yield*this.step()):a.start.push(this.sourceToken);return;case"anchor":case"tag":case"space":case"comment":case"newline":a.start.push(this.sourceToken);return}let b=this.startBlockValue(a);b?this.stack.push(b):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(a){if("map-value-ind"===this.type){let b,c=k(j(this.peek(2)));a.end?((b=a.end).push(this.sourceToken),delete a.end):b=[this.sourceToken];let d={type:"block-map",offset:a.offset,indent:a.indent,items:[{start:c,key:a,sep:b}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=d}else yield*this.lineEnd(a)}*blockScalar(a){switch(this.type){case"space":case"comment":case"newline":a.props.push(this.sourceToken);return;case"scalar":if(a.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let a=this.source.indexOf("\n")+1;for(;0!==a;)this.onNewLine(this.offset+a),a=this.source.indexOf("\n",a)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(a){let b=a.items[a.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,b.value){let c="end"in b.value?b.value.end:void 0,d=Array.isArray(c)?c[c.length-1]:void 0;d?.type==="comment"?c?.push(this.sourceToken):a.items.push({start:[this.sourceToken]})}else b.sep?b.sep.push(this.sourceToken):b.start.push(this.sourceToken);return;case"space":case"comment":if(b.value)a.items.push({start:[this.sourceToken]});else if(b.sep)b.sep.push(this.sourceToken);else{if(this.atIndentedComment(b.start,a.indent)){let c=a.items[a.items.length-2],d=c?.value?.end;if(Array.isArray(d)){l(d,b.start),d.push(this.sourceToken),a.items.pop();return}}b.start.push(this.sourceToken)}return}if(this.indent>=a.indent){let c=!this.onKeyLine&&this.indent===a.indent,d=c&&(b.sep||b.explicitKey)&&"seq-item-ind"!==this.type,e=[];if(d&&b.sep&&!b.value){let c=[];for(let d=0;d<b.sep.length;++d){let e=b.sep[d];switch(e.type){case"newline":c.push(d);break;case"space":break;case"comment":e.indent>a.indent&&(c.length=0);break;default:c.length=0}}c.length>=2&&(e=b.sep.splice(c[1]))}switch(this.type){case"anchor":case"tag":d||b.value?(e.push(this.sourceToken),a.items.push({start:e}),this.onKeyLine=!0):b.sep?b.sep.push(this.sourceToken):b.start.push(this.sourceToken);return;case"explicit-key-ind":b.sep||b.explicitKey?d||b.value?(e.push(this.sourceToken),a.items.push({start:e,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}):(b.start.push(this.sourceToken),b.explicitKey=!0),this.onKeyLine=!0;return;case"map-value-ind":if(b.explicitKey)if(b.sep)if(b.value)a.items.push({start:[],key:null,sep:[this.sourceToken]});else if(g(b.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]});else if(i(b.key)&&!g(b.sep,"newline")){let a=k(b.start),c=b.key,d=b.sep;d.push(this.sourceToken),delete b.key,delete b.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:c,sep:d}]})}else e.length>0?b.sep=b.sep.concat(e,this.sourceToken):b.sep.push(this.sourceToken);else if(g(b.start,"newline"))Object.assign(b,{key:null,sep:[this.sourceToken]});else{let a=k(b.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else b.sep?b.value||d?a.items.push({start:e,key:null,sep:[this.sourceToken]}):g(b.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):b.sep.push(this.sourceToken):Object.assign(b,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let c=this.flowScalar(this.type);d||b.value?(a.items.push({start:e,key:c,sep:[]}),this.onKeyLine=!0):b.sep?this.stack.push(c):(Object.assign(b,{key:c,sep:[]}),this.onKeyLine=!0);return}default:{let d=this.startBlockValue(a);if(d){if("block-seq"===d.type){if(!b.explicitKey&&b.sep&&!g(b.sep,"newline"))return void(yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source}))}else c&&a.items.push({start:e});this.stack.push(d);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(a){let b=a.items[a.items.length-1];switch(this.type){case"newline":if(b.value){let c="end"in b.value?b.value.end:void 0,d=Array.isArray(c)?c[c.length-1]:void 0;d?.type==="comment"?c?.push(this.sourceToken):a.items.push({start:[this.sourceToken]})}else b.start.push(this.sourceToken);return;case"space":case"comment":if(b.value)a.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(b.start,a.indent)){let c=a.items[a.items.length-2],d=c?.value?.end;if(Array.isArray(d)){l(d,b.start),d.push(this.sourceToken),a.items.pop();return}}b.start.push(this.sourceToken)}return;case"anchor":case"tag":if(b.value||this.indent<=a.indent)break;b.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==a.indent)break;b.value||g(b.start,"seq-item-ind")?a.items.push({start:[this.sourceToken]}):b.start.push(this.sourceToken);return}if(this.indent>a.indent){let b=this.startBlockValue(a);if(b)return void this.stack.push(b)}yield*this.pop(),yield*this.step()}*flowCollection(a){let b=a.items[a.items.length-1];if("flow-error-end"===this.type){let a;do yield*this.pop(),a=this.peek(1);while(a?.type==="flow-collection")}else if(0===a.end.length){switch(this.type){case"comma":case"explicit-key-ind":!b||b.sep?a.items.push({start:[this.sourceToken]}):b.start.push(this.sourceToken);return;case"map-value-ind":!b||b.value?a.items.push({start:[],key:null,sep:[this.sourceToken]}):b.sep?b.sep.push(this.sourceToken):Object.assign(b,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!b||b.value?a.items.push({start:[this.sourceToken]}):b.sep?b.sep.push(this.sourceToken):b.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let c=this.flowScalar(this.type);!b||b.value?a.items.push({start:[],key:c,sep:[]}):b.sep?this.stack.push(c):Object.assign(b,{key:c,sep:[]});return}case"flow-map-end":case"flow-seq-end":a.end.push(this.sourceToken);return}let c=this.startBlockValue(a);c?this.stack.push(c):(yield*this.pop(),yield*this.step())}else{let b=this.peek(2);if("block-map"!==b.type||("map-value-ind"!==this.type||b.indent!==a.indent)&&("newline"!==this.type||b.items[b.items.length-1].sep))if("map-value-ind"===this.type&&"flow-collection"!==b.type){let c=k(j(b));m(a);let d=a.end.splice(1,a.end.length);d.push(this.sourceToken);let e={type:"block-map",offset:a.offset,indent:a.indent,items:[{start:c,key:a,sep:d}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=e}else yield*this.lineEnd(a);else yield*this.pop(),yield*this.step()}}flowScalar(a){if(this.onNewLine){let a=this.source.indexOf("\n")+1;for(;0!==a;)this.onNewLine(this.offset+a),a=this.source.indexOf("\n",a)+1}return{type:a,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(a){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let b=k(j(a));return b.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:b,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let b=k(j(a));return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:b,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(a,b){return"comment"===this.type&&!(this.indent<=b)&&a.every(a=>"newline"===a.type||"space"===a.type)}*documentEnd(a){"doc-mode"!==this.type&&(a.end?a.end.push(this.sourceToken):a.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop()))}*lineEnd(a){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:a.end?a.end.push(this.sourceToken):a.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop())}}}},5013,(a,b,c)=>{"use strict";var d=a.r(719662),e=a.r(885774),f=a.r(725717),g=a.r(918114),h=a.r(927267),i=a.r(746987),j=a.r(309575);function k(a){let b=!1!==a.prettyErrors;return{lineCounter:a.lineCounter||b&&new i.LineCounter||null,prettyErrors:b}}function l(a,b={}){let{lineCounter:c,prettyErrors:e}=k(b),g=new j.Parser(c?.addNewLine),h=new d.Composer(b),i=null;for(let b of h.compose(g.parse(a),!0,a.length))if(i){if("silent"!==i.options.logLevel){i.errors.push(new f.YAMLParseError(b.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}else i=b;return e&&c&&(i.errors.forEach(f.prettifyError(a,c)),i.warnings.forEach(f.prettifyError(a,c))),i}c.parse=function(a,b,c){let d;"function"==typeof b?d=b:void 0===c&&b&&"object"==typeof b&&(c=b);let e=l(a,c);if(!e)return null;if(e.warnings.forEach(a=>g.warn(e.options.logLevel,a)),e.errors.length>0)if("silent"!==e.options.logLevel)throw e.errors[0];else e.errors=[];return e.toJS(Object.assign({reviver:d},c))},c.parseAllDocuments=function(a,b={}){let{lineCounter:c,prettyErrors:e}=k(b),g=new j.Parser(c?.addNewLine),h=new d.Composer(b),i=Array.from(h.compose(g.parse(a)));if(e&&c)for(let b of i)b.errors.forEach(f.prettifyError(a,c)),b.warnings.forEach(f.prettifyError(a,c));return i.length>0?i:Object.assign([],{empty:!0},h.streamInfo())},c.parseDocument=l,c.stringify=function(a,b,c){let d=null;if("function"==typeof b||Array.isArray(b)?d=b:void 0===c&&b&&(c=b),"string"==typeof c&&(c=c.length),"number"==typeof c){let a=Math.round(c);c=a<1?void 0:a>8?{indent:8}:{indent:a}}if(void 0===a){let{keepUndefined:a}=c??b??{};if(!a)return}return h.isDocument(a)&&!d?a.toString(c):new e.Document(a,d,c).toString(c)}},622650,(a,b,c)=>{"use strict";var d=a.r(719662),e=a.r(885774),f=a.r(798027),g=a.r(725717),h=a.r(421562),i=a.r(927267),j=a.r(417602),k=a.r(427853),l=a.r(147544),m=a.r(907621),n=a.r(2704),o=a.r(66326),p=a.r(746987),q=a.r(309575),r=a.r(5013),s=a.r(685927);c.Composer=d.Composer,c.Document=e.Document,c.Schema=f.Schema,c.YAMLError=g.YAMLError,c.YAMLParseError=g.YAMLParseError,c.YAMLWarning=g.YAMLWarning,c.Alias=h.Alias,c.isAlias=i.isAlias,c.isCollection=i.isCollection,c.isDocument=i.isDocument,c.isMap=i.isMap,c.isNode=i.isNode,c.isPair=i.isPair,c.isScalar=i.isScalar,c.isSeq=i.isSeq,c.Pair=j.Pair,c.Scalar=k.Scalar,c.YAMLMap=l.YAMLMap,c.YAMLSeq=m.YAMLSeq,c.CST=n,c.Lexer=o.Lexer,c.LineCounter=p.LineCounter,c.Parser=q.Parser,c.parse=r.parse,c.parseAllDocuments=r.parseAllDocuments,c.parseDocument=r.parseDocument,c.stringify=r.stringify,c.visit=s.visit,c.visitAsync=s.visitAsync}];
|
|
240
250
|
|
|
241
|
-
//# sourceMappingURL=
|
|
251
|
+
//# sourceMappingURL=_1lz_cq2._.js.map
|