thursday-agent 0.8.0 → 0.9.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.nft.json +1 -1
- package/.next/server/app/api/bot/keep-working/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/memory/files/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/memory/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/thread/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/bot/thread/route.js.nft.json +1 -1
- package/.next/server/app/api/config/route.js.nft.json +1 -1
- package/.next/server/app/api/events/route.js.nft.json +1 -1
- package/.next/server/app/api/favicon/[host]/route.js.nft.json +1 -1
- package/.next/server/app/api/file/[...path]/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/catalog/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/credits/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/route.js.nft.json +1 -1
- package/.next/server/app/api/llm-model/subscription/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/[name]/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/oauth/callback/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/route.js.nft.json +1 -1
- package/.next/server/app/api/mcp/tools/route.js.nft.json +1 -1
- package/.next/server/app/api/memory/edit/route.js +1 -1
- 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/probe/route.js.nft.json +1 -1
- package/.next/server/app/api/reach/route.js +11 -11
- package/.next/server/app/api/reach/route.js.nft.json +1 -1
- package/.next/server/app/api/routine/route.js +6 -6
- package/.next/server/app/api/routine/route.js.nft.json +1 -1
- package/.next/server/app/api/signins/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.nft.json +1 -1
- package/.next/server/app/api/thursday/skills/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/text/route.js +11 -11
- package/.next/server/app/api/thursday/text/route.js.nft.json +1 -1
- package/.next/server/app/api/thursday/tool-call/route.js +6 -6
- package/.next/server/app/api/thursday/tool-call/route.js.nft.json +1 -1
- package/.next/server/app/api/workspace/files/route.js.nft.json +1 -1
- package/.next/server/app/api/workspace/route.js.nft.json +1 -1
- package/.next/server/app/artifact/[...path]/page/server-reference-manifest.json +1 -1
- package/.next/server/app/artifact/[...path]/page.js.nft.json +1 -1
- package/.next/server/app/artifact/[...path]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/favicon.ico/route.js.nft.json +1 -1
- package/.next/server/app/manifest.webmanifest/route.js.nft.json +1 -1
- package/.next/server/app/page/server-reference-manifest.json +56 -56
- 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]__012s2o8._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__04r4h-2._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0mrk2it._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0nmhgeo._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1fy2g82._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1ndi14y._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1nmflqk._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1v7-zke._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1wnzmx9._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1xv-5cq._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1ygplx1._.js +1 -1
- package/.next/server/chunks/_05v8k21._.js +1 -1
- package/.next/server/chunks/_0awtznl._.js +4 -4
- package/.next/server/chunks/_0k6qjcf._.js +1 -1
- package/.next/server/chunks/_0na2fj1._.js +5 -5
- package/.next/server/chunks/_0x-ej3f._.js +21 -21
- package/.next/server/chunks/_1dc_d1q._.js +22 -20
- package/.next/server/chunks/_1jc5g4p._.js +2 -2
- package/.next/server/chunks/_1jn-aep._.js +50 -48
- package/.next/server/chunks/{_1u8ygbz._.js → _1m88lkh._.js} +7 -7
- package/.next/server/chunks/_1uuucy-._.js +4 -4
- package/.next/server/chunks/_1v9r2ke._.js +1 -1
- package/.next/server/chunks/ssr/{[root-of-the-server]__1h4bnrf._.js → [root-of-the-server]__0oo-wlv._.js} +2 -2
- package/.next/server/chunks/ssr/{[root-of-the-server]__1kyi568._.js → [root-of-the-server]__0tvavy9._.js} +1 -1
- package/.next/server/chunks/ssr/[root-of-the-server]__0tzekbl._.js +1 -1
- package/.next/server/chunks/ssr/[root-of-the-server]__0zuns7e._.js +3 -0
- package/.next/server/chunks/ssr/[root-of-the-server]__1se25x0._.js +1 -1
- package/.next/server/chunks/ssr/{_1i3ddn7._.js → _05pl_u8._.js} +1 -1
- package/.next/server/chunks/ssr/_070nv1_._.js +3 -0
- package/.next/server/chunks/ssr/_097-ljd._.js +1 -1
- package/.next/server/chunks/ssr/_0dshsh4._.js +3 -0
- package/.next/server/chunks/ssr/_0fqhhwi._.js +1 -1
- package/.next/server/chunks/ssr/{_0z8jpch._.js → _0ital-2._.js} +2 -2
- package/.next/server/chunks/ssr/{_19g570d._.js → _0kjj5ts._.js} +3 -3
- package/.next/server/chunks/ssr/{_1nod5hh._.js → _0l_mcfz._.js} +2 -2
- package/.next/server/chunks/ssr/_0ld9_qq._.js +1 -1
- package/.next/server/chunks/ssr/_0ltz2q5._.js +3 -0
- package/.next/server/chunks/ssr/_0scf7xy._.js +3 -0
- package/.next/server/chunks/ssr/_0u5xv6g._.js +3 -0
- package/.next/server/chunks/ssr/{_0ewory0._.js → _0urj3mc._.js} +2 -2
- package/.next/server/chunks/ssr/{_0pm-2p-._.js → _1-zyvdb._.js} +2 -2
- package/.next/server/chunks/ssr/{_1_rqu8x._.js → _12mijol._.js} +7 -7
- package/.next/server/chunks/ssr/_15zqt-t._.js +1 -1
- package/.next/server/chunks/ssr/_184327j._.js +1 -1
- package/.next/server/chunks/ssr/{_1y-ea28._.js → _1a-nuxx._.js} +2 -2
- package/.next/server/chunks/ssr/_1alxym6._.js +3 -0
- package/.next/server/chunks/ssr/{_0hzz82u._.js → _1d423aj._.js} +25 -23
- package/.next/server/chunks/ssr/{_1u1mxu9._.js → _1flbs77._.js} +2 -2
- package/.next/server/chunks/ssr/_1mqn9mc._.js +1 -1
- package/.next/server/chunks/ssr/_1neoj22._.js +1 -1
- package/.next/server/chunks/ssr/{_1oijqjw._.js → _1tmu8z-._.js} +2 -2
- package/.next/server/chunks/ssr/{_10y6r1n._.js → _1uy0xom._.js} +3 -3
- package/.next/server/chunks/ssr/_1x-kojb._.js +20 -0
- package/.next/server/chunks/ssr/_1xoch6f._.js +1 -1
- package/.next/server/chunks/ssr/_1z74dmq._.js +164 -0
- package/.next/server/chunks/ssr/features_bot_1nr94ks._.js +3 -0
- package/.next/server/chunks/ssr/features_bot_1s_-2vj._.js +1 -1
- package/.next/server/chunks/ssr/features_connectors_components_mcp-setting_tsx_0jmbgvp._.js +1 -1
- package/.next/server/chunks/ssr/features_memory_components_memory-setting_tsx_0oa43sw._.js +1 -1
- package/.next/server/chunks/ssr/features_routine_components_routine-setting_tsx_055fknz._.js +1 -1
- package/.next/server/chunks/ssr/{node_modules_111sh9o._.js → node_modules_03d0rfz._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0lg75qx._.js → node_modules_04_sbbc._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_10gbm2y._.js → node_modules_05ybmta._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1v9tc1c._.js → node_modules_068ws5v._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1_8mv4v._.js → node_modules_06bb4q8._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_01f8_se._.js → node_modules_07rs_p2._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0ii1l89._.js → node_modules_0dzm4um._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_20xmwtu._.js → node_modules_0jljel9._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1ix-g49._.js → node_modules_0sgy-dc._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0woscox._.js → node_modules_0t_ez6-._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_059vtf2._.js → node_modules_0th357h._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_06w645b._.js → node_modules_0ubdtk-._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0b8df3s._.js → node_modules_0uyh_vb._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_07ih6wb._.js → node_modules_0wnlddw._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0gt-uw9._.js → node_modules_0x630an._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1x825hz._.js → node_modules_0yvz9e0._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0t-44lj._.js → node_modules_12et8d5._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1m3gb16._.js → node_modules_13kwejm._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1p9rdsy._.js → node_modules_1af3w91._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0sz5yg1._.js → node_modules_1bucjlk._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1teyzfa._.js → node_modules_1lkix61._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1lsyy7k._.js → node_modules_1ogczzz._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_1-7qawg._.js → node_modules_1s-gb-1._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_0yv-re6._.js → node_modules_1uwg-gz._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_03ptrl9._.js → node_modules_1wbkzl9._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_00jv9_3._.js → node_modules_1z1lrbk._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@base-ui_react_0jne69c._.js → node_modules_@base-ui_react_0buz1-j._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_00q1oa3._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0r443fh._.js} +1 -1
- package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1-2_5z7._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_10wnlbk._.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 +57 -57
- package/.next/static/chunks/06nt9tatr-dug.js +1 -0
- package/.next/static/chunks/0_awn8tucznxc.js +1 -0
- package/.next/static/chunks/{34s52v8f841zo.js → 0ge-hx0ed83a1.js} +1 -1
- package/.next/static/chunks/0pda_vf-abwvx.js +1 -0
- package/.next/static/chunks/{2u9yjkpkoij75.js → 0qmd8n52hp-6v.js} +1 -1
- package/.next/static/chunks/0rowp9rx3qbxu.js +18 -0
- package/.next/static/chunks/{1ocy4w0v20a3v.js → 13ixzheqw7o-w.js} +2 -2
- package/.next/static/chunks/1grkt5gr8pbg1.js +17 -0
- package/.next/static/chunks/{21gf2t_whhurc.js → 1yugpvvi8qrbu.js} +2 -2
- package/.next/static/chunks/{1e4yrzs5evq_r.js → 245hb85nsy6j4.js} +1 -1
- package/.next/static/chunks/27lkanxvtdn09.js +1 -0
- package/.next/static/chunks/{0oz7a68qanm99.js → 27tvv1i-smrck.js} +1 -1
- package/.next/static/chunks/{2zhfdbq50ee5i.js → 2c64drdevdla3.js} +1 -1
- package/.next/static/chunks/{0k5tkt_qi52kb.js → 2ndw4w4u2x51r.js} +1 -1
- package/.next/static/chunks/37j27b3e1gt7r.js +1 -0
- package/.next/static/chunks/{2om4lkg86feb4.js → 38301ji-85i30.js} +1 -1
- package/.next/static/chunks/{09c13vnqy7al3.js → 3bbzsitgiltnt.js} +2 -2
- package/.next/static/chunks/3fec-aeteddr-.js +1 -0
- package/.next/static/chunks/3go3hwp1z2_h2.css +1 -0
- package/.next/static/chunks/3h2bun3hcggg8.js +1 -0
- package/.next/static/chunks/{0g1p98s2pfx2w.js → 3h2e-xv1zxh_f.js} +2 -2
- package/.next/static/chunks/3j1y335o95mj7.js +1 -0
- package/.next/static/chunks/3obf9n3cxj99k.js +1 -0
- package/.next/static/chunks/{2upc9mkcc3nlq.js → 427qsc6kahxyo.js} +1 -1
- package/README.md +31 -14
- package/bin/port.mjs +11 -7
- package/bin/thursday.mjs +1 -1
- package/components/ui/radio-group.tsx +2 -2
- package/components/ui/shiny-text.tsx +3 -22
- package/docs/how-it-works.md +11 -3
- package/docs/images/first-run.png +0 -0
- package/docs/images/keeps-going.png +0 -0
- package/docs/images/two-minds.png +0 -0
- package/features/ai/components/model-browser.tsx +1 -1
- package/features/ai/components/model-picker.tsx +1 -1
- package/features/ai/guide.ts +9 -4
- package/features/ai/prompts/bot.prompt.ts +4 -1
- package/features/ai/tools/routine.tool.ts +28 -16
- package/features/bot/bot.runner.ts +3 -1
- package/features/bot/components/bot-mark.tsx +6 -1
- package/features/bot/components/bot-setting.tsx +2 -4
- package/features/bot/components/bot-tool.tsx +2 -0
- package/features/bot/components/room-list.tsx +12 -3
- package/features/bot/components/room-pill.tsx +26 -19
- package/features/config/components/config-setting.tsx +17 -5
- package/features/config/components/voice-key.tsx +38 -18
- package/features/connectors/mcp.const.ts +90 -59
- package/features/intro/components/intro.tsx +50 -27
- package/features/routine/components/routine-mark.tsx +4 -6
- package/features/routine/components/routine-setting.tsx +332 -143
- package/features/routine/routine.query.ts +24 -3
- package/features/routine/routine.schema.ts +55 -4
- package/features/settings/components/install-app.tsx +1 -4
- package/features/settings/components/setting-ui.tsx +1 -1
- package/features/skills/skills.discover.ts +2 -1
- package/features/skills/skills.query.ts +5 -1
- package/features/skills/skills.schema.ts +2 -0
- package/features/thursday/components/ascii-orb.tsx +39 -10
- package/features/thursday/components/connect-wave.tsx +284 -0
- package/features/thursday/components/side-captions.tsx +29 -17
- package/features/thursday/components/thursday-setting.tsx +2 -2
- package/features/thursday/components/thursday.tsx +130 -58
- package/features/thursday/components/voice-picker.tsx +1 -1
- package/features/thursday/components/write-line.tsx +2 -2
- package/features/thursday/open-work.ts +11 -3
- package/features/thursday/tool-line.ts +94 -12
- package/features/thursday/use-text-call.ts +3 -2
- package/features/thursday/use-thursday.ts +5 -2
- package/features/workspace/components/artifact-view.tsx +129 -7
- package/guide/bots.md +17 -5
- package/guide/calls.md +15 -7
- package/guide/setup.md +10 -2
- package/lib/desktop-notify.ts +3 -2
- package/package.json +1 -1
- package/scripts/bot-context.test.mts +1 -1
- package/skills/computer/SKILL.md +1 -0
- package/skills/interactive-page/SKILL.md +4 -0
- package/.next/server/chunks/[root-of-the-server]__0n-l_n_._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0wvo2of._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1e6aut3._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1ziojdq._.js +0 -3
- package/.next/server/chunks/ssr/[root-of-the-server]__1srp8l5._.js +0 -3
- package/.next/server/chunks/ssr/_0mes4s0._.js +0 -3
- package/.next/server/chunks/ssr/_0ya0cb0._.js +0 -3
- package/.next/server/chunks/ssr/_0yto5s7._.js +0 -20
- package/.next/server/chunks/ssr/_10dw2nv._.js +0 -3
- package/.next/server/chunks/ssr/_1p0gxeo._.js +0 -164
- package/.next/server/chunks/ssr/_1r41yvh._.js +0 -3
- package/.next/server/chunks/ssr/_1r79ksv._.js +0 -3
- package/.next/server/chunks/ssr/features_bot_1ogjt52._.js +0 -3
- package/.next/server/chunks/ssr/node_modules_@base-ui_react_0b3d4m9._.js +0 -3
- package/.next/static/chunks/03omwz_vi2ndg.js +0 -1
- package/.next/static/chunks/0_1bqgd6wt_og.js +0 -1
- package/.next/static/chunks/0abgkzikaznxc.js +0 -1
- package/.next/static/chunks/0bddkpash59-o.js +0 -17
- package/.next/static/chunks/0c2-bzhy3a0ib.js +0 -1
- package/.next/static/chunks/0iilfb1ocevnx.js +0 -1
- package/.next/static/chunks/0imbhx-j830a_.css +0 -1
- package/.next/static/chunks/24h1y9dhy3m_2.js +0 -1
- package/.next/static/chunks/2be08eqxsfc1y.js +0 -1
- package/.next/static/chunks/2d3yhjtafgmtw.js +0 -1
- package/.next/static/chunks/2f_5saocsko_b.js +0 -1
- package/.next/static/chunks/2lwbr5vx0ixaj.js +0 -18
- package/.next/static/chunks/44kjmi5h_p8px.js +0 -1
- /package/.next/static/{UiOMPYpQ4fqGyu5PzS-7j → u8kJqShUAa49vY7BxAWsw}/_buildManifest.js +0 -0
- /package/.next/static/{UiOMPYpQ4fqGyu5PzS-7j → u8kJqShUAa49vY7BxAWsw}/_clientMiddlewareManifest.js +0 -0
- /package/.next/static/{UiOMPYpQ4fqGyu5PzS-7j → u8kJqShUAa49vY7BxAWsw}/_ssgManifest.js +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
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(875931),h=a.i(938934),i=a.i(978876),j=a.i(375827),k=a.i(467650),l=a.i(138902),m=a.i(345846),n=a.i(617594),o=a.i(622547),p=a.i(382442),q=a.i(451017),r=a.i(762008),s=a.i(547613),t=a.i(446957),u=a.i(138100),v=a.i(569549),w=a.i(821415),x=a.i(706210),y=a.i(176668),z=a.i(293480),A=a.i(987674),B=a.i(182248),C=b([g,i,l,m,n,o,v]);async function D(b){let{listThreadOverview:c}=await a.A(343064),d=await c();if(!d.length)return"No thread has been started yet.";let e=d.map(a=>`"${a.label}" (${a.bot}, ${a.status})`).join(", ");return`There is no thread called "${b}". The latest are: ${e}. Call again with one of those labels.`}async function E(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,A.estimateTokens)(f)+(0,A.estimateTokens)(JSON.stringify(b))})}c.sort((a,b)=>b.tokens-a.tokens);let e=c.reduce((a,b)=>a+b.tokens,0);y.logger.debug(`${a} tools ${e} tokens over ${c.length} — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`)}async function F(a){let b=await G(a);return f.IS_DEV&&await E(a.target,b),b}async function G(b){if("memory-edit"===b.target){let a=(0,m.createMemoryTools)("user",null,{countReads:!1});return{[r.TOOL_NAMES.memory_recall]:a[r.TOOL_NAMES.memory_recall],[r.TOOL_NAMES.memory_remember]:a[r.TOOL_NAMES.memory_remember],[r.TOOL_NAMES.memory_forget]:a[r.TOOL_NAMES.memory_forget]}}let{[r.TOOL_NAMES.memory_conversation]:c,...y}=(0,m.createMemoryTools)("call","thursday"===b.target?b.callId??null:null),A={[r.TOOL_NAMES.memory_conversation]:c},C=await (0,w.openWorkspace)();if("thursday"===b.target){var E;let c,g,l=await (0,v.readCallSkillsOn)()?(0,q.createSkillTools)({sandbox:C,skills:await (0,u.loadSkills)(C)}):{};return{...y,...A,...l,...(0,s.createWorkspaceTools)(C,{write:!1,timeoutMs:f.CALL_EXEC_TIMEOUT_MS}),...!1===b.webSearch?{}:await (0,o.createCallSearchTool)(C),...(E=b.callId,c=async b=>{let{resolveThread:c}=await a.A(343064);return(b.trim()?await c(b.trim()):null)??await D(b)},g=async(b,c,d)=>{let e=await a.A(763543);try{return await e.answerThread(b,c,"thursday",d)}catch(a){if((0,z.isPublicError)(a))return a.message;throw a}},{[r.TOOL_NAMES.thread_start]:(0,d.tool)({description:i.threadStartSpec.description,inputSchema:i.threadStartSpec.parameters,execute:async({bot:b,request:c,label:d})=>{let{findJobBot:e,listJobBots:f}=await a.A(276307),g=await e(b);if(!g||g.disabled){let a=(await f()).map(a=>a.name);return`There is no bot called "${b}". The bots are: ${a.join(", ")}. Nothing was started — call again with one of those.`}let{startThread:h}=await a.A(763543);return{threadId:await h({bot:g.name,request:c,label:d,callId:E,from:"thursday"}),note:`${g.name} has "${d}". Its updates reach the conversation on their own. Anything further about this work — a correction, the next step once it finishes — is \`${r.TOOL_NAMES.thread_tell}\` with "${d}"; a question it asks is answered with \`${r.TOOL_NAMES.thread_answer}\`.`}}}),[r.TOOL_NAMES.thread_tell]:(0,d.tool)({description:i.threadTellSpec.description,inputSchema:i.threadTellSpec.parameters,execute:async({thread:a,words:b})=>{let d=await c(a);if("string"==typeof d)return d;if(!b.trim())return"Say what to pass on.";let e=await g(d.id,b.trim());return"string"==typeof e?e:e?.answered?{label:d.label,answered:e.answered,note:`${e.answered.bot} was waiting on a question, and took this as its answer.`}:{label:d.label,bot:e?.to??d.bot,status:"running",note:"running"===d.status?"The bot reads it before its next step.":"The bot picks the thread back up from there."}}}),[r.TOOL_NAMES.thread_answer]:(0,d.tool)({description:i.threadAnswerSpec.description,inputSchema:i.threadAnswerSpec.parameters,execute:async({thread:b,bot:d,answer:e})=>{let f=await c(b);if("string"==typeof f)return f;if(!e.trim())return"Say what the answer is.";let{findThreadView:h}=await a.A(343064),i=(await h(f.id))?.room.questions??[],j=i.find(a=>a.bot.toLowerCase()===d.trim().toLowerCase());if(!j)return i.length?`${d} is not asking anything in "${f.label}". Waiting there: ${i.map(a=>a.bot).join(", ")}. Call again with that bot.`:`No question is waiting in "${f.label}". To say something else to it, use \`${r.TOOL_NAMES.thread_tell}\`.`;let k=await g(f.id,e.trim(),j.bot);return"string"==typeof k?k:{label:f.label,answered:k?.answered??{bot:j.bot,question:j.text},note:`${j.bot} has the answer to its question and goes on from it.`}}}),[r.TOOL_NAMES.thread_status]:(0,d.tool)({description:i.threadStatusSpec.description,inputSchema:i.threadStatusSpec.parameters,execute:async({thread:b})=>{let{listThreadOverview:d,findThreadView:f}=await a.A(343064),g={now:(0,h.clockNow)()},i=a=>(0,e.formatDistanceToNowStrict)((0,x.toDate)(a),{addSuffix:!0});if(!(!b.trim()||"all"===b.trim().toLowerCase())){let a=await c(b);if("string"==typeof a)return a;let d=(await f(a.id))?.room;return{...g,label:a.label,id:a.id,bot:a.bot,participants:d?.participants??[],questions:d?.questions??[],status:a.status,since:i(a.updatedAt),outcome:a.outcome,..."waiting"===a.status&&a.pending?.options.length?{options:a.pending.options}:{}}}let j=await d();return j.length?{...g,threads:j.map(a=>({id:a.id,label:a.label,bot:a.bot,status:a.status,participants:a.room.participants,questions:a.room.questions.map(a=>({...a,text:(0,B.clip)(a.text,200)})),since:i(a.updatedAt),...a.ask?{asking:a.ask.question,options:a.ask.options}:{},..."running"===a.status?{now:(0,t.threadActivity)(a.lines)}:{},...a.outcome&&"waiting"!==a.status?{outcome:(0,B.clip)(a.outcome,200)}:{}}))}:"No thread has been started yet."}}),[r.TOOL_NAMES.thread_cancel]:(0,d.tool)({description:i.threadCancelSpec.description,inputSchema:i.threadCancelSpec.parameters,execute:async({thread:b})=>{let d=await c(b);if("string"==typeof d)return d;let{cancelThread:e}=await a.A(763543);return await e(d.id),{label:d.label,status:"cancelled"}}}),[r.TOOL_NAMES.thread_show]:(0,d.tool)({description:i.threadShowSpec.description,inputSchema:i.threadShowSpec.parameters,execute:async({thread:b})=>{let d=await c(b);if("string"==typeof d)return d;let{appEvents:e}=await a.A(133300),{filesOnDisk:f}=await a.A(122690),{opensOnFinish:g,pathsIn:h}=await a.A(394298),i=await f(h(d.outcome??""),null);if(!i.length)return e.emit({type:"showThread",threadId:d.id}),{label:d.label,showing:"the thread"};let j=Math.max(0,i.findIndex(g));e.emit({type:"showFile",paths:[i[j],...i.filter((a,b)=>b!==j)]});let{markSeen:k}=await a.A(343064);return await k([d.id]),{label:d.label,showing:i[j]}}}),[r.TOOL_NAMES.thread_seen]:(0,d.tool)({description:i.threadSeenSpec.description,inputSchema:i.threadSeenSpec.parameters,execute:async({thread:b})=>{let d=await c(b);if("string"==typeof d)return d;let{markSeen:e}=await a.A(343064);return await e([d.id]),{label:d.label,seen:!0}}})}),...(0,n.createRoutineTools)(),...b.written?(0,k.createLookTool)():(0,j.callTools)()}}let F=await (0,u.loadSkills)(C,b.bot);return{[r.TOOL_NAMES.memory_recall]:y[r.TOOL_NAMES.memory_recall],...A,...await (0,o.createSearchTool)(b.model,C),...(0,s.createWorkspaceTools)(C,{write:!0,env:{...(0,w.jobShellEnv)(b.session),...(0,w.botShellEnv)(b.bot)},guide:!0,bot:b.bot}),...await (0,l.createMcpTools)(b.bot,C),...(0,q.createSkillTools)({sandbox:C,skills:F,bot:b.bot}),...b.model&&(0,g.seesToolImages)(b.model.ref)?(0,k.createLookTool)():{},...(0,p.createSignInTools)(C,b.bot,(0,w.jobShellEnv)(b.session)),...await (0,i.createThreadRecallTool)(b.bot,b.thread??null)}}[g,i,l,m,n,o,v]=C.then?(await C)():C,a.s(["loadTools",0,F]),c()}catch(a){c(a)}},!1),875931,a=>a.a(async(b,c)=>{try{var d=a.i(938537),e=a.i(674861),f=a.i(606016),g=a.i(388319),h=a.i(538177),i=a.i(767071),j=a.i(140358),k=a.i(873739),l=a.i(899042),m=a.i(345364),n=a.i(434451),o=a.i(655819),p=a.i(652685),q=a.i(438766),r=a.i(47919);a.i(569572);var s=a.i(688034),t=a.i(725466),u=a.i(176668),v=a.i(293480),w=a.i(182248),x=a.i(652619),y=a.i(689656),z=b([t,x]);[t,x]=z.then?(await z)():z;let K=/context[ _-]?(length|window)|maximum context|prompt is too long|too many (input )?tokens|input token count|exceeds? the (maximum|model'?s?) (context|input|prompt|number of tokens)|maximum prompt length|request (entity )?too large/i;function A(a){return B(a).some(a=>{let{statusCode:b,message:c,error:d}=a;if(void 0!==b&&400!==b&&413!==b)return!1;let e=p.APICallError.isInstance(a)?a.responseBody:null;return[c,d,e].some(a=>"string"==typeof a&&K.test(a))})}let L=new Set([408,409,429]);function B(a){let b=[],c=[a];for(;c.length&&b.length<12;){let a=c.shift();!("object"!=typeof a||null===a||b.includes(a))&&(b.push(a),r.RetryError.isInstance(a)&&c.push(...a.errors),"cause"in a&&c.push(a.cause))}return b}let M=(a,b)=>({ref:a,model:b,searchTools:null}),N=null;function C(a){if(null==a||""===a)return null;let b=Number(a);return Number.isFinite(b)?Math.round(1e6*b*1e4)/1e4:null}async function D(){if(N&&Date.now()-N.at<6e5)return N.models;let a=await fetch("https://ai-gateway.vercel.sh/v1/models",{headers:{accept:"application/json"}}).catch(a=>{u.logger.warn({cause:a},"gateway catalog unreachable"),(0,v.publicError)("Could not reach the gateway")});a.ok||(0,v.publicError)(`The gateway answered ${a.status}`);let b=((await a.json()).data??[]).filter(a=>!!a.id).map(a=>({id:a.id,label:a.name||a.id,owner:a.owned_by||a.id.slice(0,a.id.indexOf("/")),type:a.type??null,tags:a.tags??[],price:function(a){let b=a.pricing??{},c=C(b.input),d=C(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 N={at:Date.now(),models:b},b}async function E(a,b){if(b&&b>0)return b;let c="vercel-ai-gateway"===a.provider?await D().catch(()=>[]):[];return(0,y.compactAtFor)((0,y.contextWindowOf)(a.provider,a.model,c))}async function F(){return await D().then(a=>new Set(a.map(a=>a.id))).catch(()=>null)}async function G(a,b){if("vercel-ai-gateway"!==a)return b;let c=await F();if(!c)return b;let d=b.filter(a=>c.has(a.id));return d.length>0?d:b}async function H(a){let{label:b,apiKeyName:c,signIn:p}=y.TEXT_MODEL_PROVIDERS[a.provider],r=await (0,t.readConfig)(c);return r||(0,v.publicError)(p?`${b} is not signed in — sign in from Config.`:`No ${b} key — add one in Config.`),function(a,b){switch(a.provider){case"openai":{let c=(0,m.createOpenAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"chatgpt":return{ref:a,model:(0,x.chatGptModel)(a.model),searchTools:null};case"anthropic":{let c=(0,d.createAnthropic)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch_20260209()}}}case"google":{let c=(0,j.createGoogleGenerativeAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.googleSearch({})}}}case"xai":{let c=(0,o.createXai)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"mistral":return M(a,(0,l.createMistral)({apiKey:b})(a.model));case"deepseek":return M(a,(0,h.createDeepSeek)({apiKey:b})(a.model));case"groq":return M(a,(0,k.createGroq)({apiKey:b})(a.model));case"cerebras":return M(a,(0,e.createCerebras)({apiKey:b})(a.model));case"togetherai":return M(a,(0,n.createTogetherAI)({apiKey:b})(a.model));case"fireworks":return M(a,(0,i.createFireworks)({apiKey:b})(a.model));case"deepinfra":return M(a,(0,g.createDeepInfra)({apiKey:b})(a.model));case"cohere":return M(a,(0,f.createCohere)({apiKey:b})(a.model));case"vercel-ai-gateway":{let c=(0,q.createGateway)({apiKey:b});return{ref:a,model:c(a.model),searchTools:null}}default:(0,v.publicError)(`Not supported provider: ${String(a.provider)}`)}}(a,r)}async function I(a){let b=async a=>(0,y.defaultModelOf)({suggestModels:await G(a.id,a.suggestModels)}),c=a?y.TEXT_MODEL_PROVIDER_LIST.find(b=>b.id===a):void 0,d=["openai","xai"].map(a=>({...y.TEXT_MODEL_PROVIDERS[a],id:a}));if(c){let a=await b(c);if(a)return{provider:c.id,model:a}}let e=(0,y.parseTextModel)(await (0,t.readConfig)(s.DEFAULT_MODEL_KEY)??void 0);if(e&&await (0,t.readConfig)(y.TEXT_MODEL_PROVIDERS[e.provider].apiKeyName))return e;for(let a of[...d,...y.TEXT_MODEL_PROVIDER_LIST]){if(!await (0,t.readConfig)(a.apiKeyName))continue;let c=await b(a);if(c)return u.logger.info(`no model set, falling back to ${a.id}/${c}`),{provider:a.id,model:c}}(0,v.publicError)("No model key is set — add one in Config")}async function J(a){let b=(0,y.parseMediaModel)(await (0,t.readConfig)(s.MEDIA_MODEL_KEYS[a]));if(!b||!(0,y.canMakeKind)(b.provider,a))return null;let c=await (0,t.readConfig)(y.MEDIA_MODEL_PROVIDERS[b.provider].apiKeyName);return c?{ref:b,apiKey:c}:null}a.s(["buildImageModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).image(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).image(a.model);case"xai":return(0,o.createXai)({apiKey:b}).image(a.model);case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).image(a.model);default:(0,v.publicError)(`Not supported image provider: ${String(a.provider)}`)}},"buildSpeechModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).speech(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).speech(a.model);case"xai":return(0,o.createXai)({apiKey:b}).speech();case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).speech(a.model);default:(0,v.publicError)(`Not supported speech provider: ${String(a.provider)}`)}},"buildTranscriptionModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).transcription(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).transcription(a.model);case"xai":return(0,o.createXai)({apiKey:b}).transcription();case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).transcription(a.model);default:(0,v.publicError)(`Not supported transcription provider: ${String(a.provider)}`)}},"buildVideoModel",0,function(a,b){switch(a.provider){case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).video(a.model);case"xai":return(0,o.createXai)({apiKey:b}).video(a.model);case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).video(a.model);default:(0,v.publicError)(`${a.provider} has no video model`)}},"compactBudget",0,E,"getTextModel",0,H,"isContextOverflow",0,A,"isProviderRefusal",0,function(a){return!A(a)&&B(a).some(a=>{let{statusCode:b}=a;return"number"==typeof b&&b>=400&&b<500&&!L.has(b)})},"modelErrorToString",0,function(a){if(!p.APICallError.isInstance(a))return(0,w.errorToString)(a);let b=a.statusCode?` (${a.statusCode})`:"",c=a.responseBody?.trim(),d=c&&!c.includes(a.message)?` ${(0,w.clip)(c,300)}`:"";return`${a.message}${b}${d}`},"resolveDefaultModel",0,I,"resolveMediaRef",0,J,"seesToolImages",0,function(a){let b=["openai","chatgpt","anthropic","google","xai"];return"vercel-ai-gateway"!==a.provider?b.includes(a.provider):b.includes(a.model.split("/")[0]??"")}]),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(446957),j=a.i(344853),k=a.i(947950),l=a.i(986743),m=a.i(138100),n=a.i(684321),o=a.i(821415),p=a.i(706210),q=a.i(182248),r=a.i(644468),s=a.i(938934),t=b([h,j,k,l,r]);async function u(a,b,c,t){var u,x,y,z,A,B,C,D,E;let F,G,H,I,J,K,L=await (0,o.openWorkspace)(),M=a.trim(),[N,O,P,Q,R,S,T,U,V]=await Promise.all([(0,m.loadSkills)(L,M),(0,l.listNoteIndex)(),(0,r.listConnectedToolNames)(),(0,k.findPinnedTools)(M),(0,h.listJobBots)(),(0,g.listBotMemory)(M),(0,h.readBotMemoryOn)(),(0,o.readMachineTools)(L),(0,j.listBotWork)(M,c?.thread??null)]),W=R.filter(a=>a.name!==M),X=[(u=M,x=c,G=(F=x?.owner??u)===u?"**You** coordinate this thread: its result goes from you to Thursday.":`**${F}** coordinates this thread and brings its result to Thursday.`,H=x?`
|
|
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),884780,a=>{"use strict";a.i(902157),a.i(912714);var b=a.i(750227),c=a.i(569572);(0,b.join)(c.APP_DIR,"guide");let d=".guide";a.s(["botGuideLine",0,()=>`How ${c.APP_NAME} itself works for the user — its screens and settings — is written under \`${d}/\` here, \`index.md\` first; read it only when the job is about the app.`,"guideLine",0,()=>`How ${c.APP_NAME} works for the person using it — its screens, its settings, what it connects to, what to do when something stops — is written under \`${d}/\` here, \`index.md\` first. Read it whenever an answer depends on how the app works: what can be asked for, where something is changed, a wish that needs a setting switched on, something that stopped or was refused. Answer from it rather than from what you assume.`])},738131,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(868468),f=a.i(569572),g=a.i(875931),h=a.i(938934),i=a.i(978876),j=a.i(375827),k=a.i(467650),l=a.i(138902),m=a.i(345846),n=a.i(617594),o=a.i(622547),p=a.i(382442),q=a.i(451017),r=a.i(762008),s=a.i(547613),t=a.i(446957),u=a.i(138100),v=a.i(569549),w=a.i(821415),x=a.i(706210),y=a.i(176668),z=a.i(293480),A=a.i(987674),B=a.i(182248),C=b([g,i,l,m,n,o,v]);async function D(b){let{listThreadOverview:c}=await a.A(343064),d=await c();if(!d.length)return"No thread has been started yet.";let e=d.map(a=>`"${a.label}" (${a.bot}, ${a.status})`).join(", ");return`There is no thread called "${b}". The latest are: ${e}. Call again with one of those labels.`}async function E(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,A.estimateTokens)(f)+(0,A.estimateTokens)(JSON.stringify(b))})}c.sort((a,b)=>b.tokens-a.tokens);let e=c.reduce((a,b)=>a+b.tokens,0);y.logger.debug(`${a} tools ${e} tokens over ${c.length} — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`)}async function F(a){let b=await G(a);return f.IS_DEV&&await E(a.target,b),b}async function G(b){if("memory-edit"===b.target){let a=(0,m.createMemoryTools)("user",null,{countReads:!1});return{[r.TOOL_NAMES.memory_recall]:a[r.TOOL_NAMES.memory_recall],[r.TOOL_NAMES.memory_remember]:a[r.TOOL_NAMES.memory_remember],[r.TOOL_NAMES.memory_forget]:a[r.TOOL_NAMES.memory_forget]}}let{[r.TOOL_NAMES.memory_conversation]:c,...y}=(0,m.createMemoryTools)("call","thursday"===b.target?b.callId??null:null),A={[r.TOOL_NAMES.memory_conversation]:c},C=await (0,w.openWorkspace)();if("thursday"===b.target){var E;let c,g,l=await (0,v.readCallSkillsOn)()?(0,q.createSkillTools)({sandbox:C,skills:await (0,u.loadSkills)(C)}):{};return{...y,...A,...l,...(0,s.createWorkspaceTools)(C,{write:!1,timeoutMs:f.CALL_EXEC_TIMEOUT_MS}),...!1===b.webSearch?{}:await (0,o.createCallSearchTool)(C),...(E=b.callId,c=async b=>{let{resolveThread:c}=await a.A(343064);return(b.trim()?await c(b.trim()):null)??await D(b)},g=async(b,c,d)=>{let e=await a.A(763543);try{return await e.answerThread(b,c,"thursday",d)}catch(a){if((0,z.isPublicError)(a))return a.message;throw a}},{[r.TOOL_NAMES.thread_start]:(0,d.tool)({description:i.threadStartSpec.description,inputSchema:i.threadStartSpec.parameters,execute:async({bot:b,request:c,label:d})=>{let{findJobBot:e,listJobBots:f}=await a.A(276307),g=await e(b);if(!g||g.disabled){let a=(await f()).map(a=>a.name);return`There is no bot called "${b}". The bots are: ${a.join(", ")}. Nothing was started — call again with one of those.`}let{startThread:h}=await a.A(763543);return{threadId:await h({bot:g.name,request:c,label:d,callId:E,from:"thursday"}),note:`${g.name} has "${d}". Its updates reach the conversation on their own. Anything further about this work — a correction, the next step once it finishes — is \`${r.TOOL_NAMES.thread_tell}\` with "${d}"; a question it asks is answered with \`${r.TOOL_NAMES.thread_answer}\`.`}}}),[r.TOOL_NAMES.thread_tell]:(0,d.tool)({description:i.threadTellSpec.description,inputSchema:i.threadTellSpec.parameters,execute:async({thread:a,words:b})=>{let d=await c(a);if("string"==typeof d)return d;if(!b.trim())return"Say what to pass on.";let e=await g(d.id,b.trim());return"string"==typeof e?e:e?.answered?{label:d.label,answered:e.answered,note:`${e.answered.bot} was waiting on a question, and took this as its answer.`}:{label:d.label,bot:e?.to??d.bot,status:"running",note:"running"===d.status?"The bot reads it before its next step.":"The bot picks the thread back up from there."}}}),[r.TOOL_NAMES.thread_answer]:(0,d.tool)({description:i.threadAnswerSpec.description,inputSchema:i.threadAnswerSpec.parameters,execute:async({thread:b,bot:d,answer:e})=>{let f=await c(b);if("string"==typeof f)return f;if(!e.trim())return"Say what the answer is.";let{findThreadView:h}=await a.A(343064),i=(await h(f.id))?.room.questions??[],j=i.find(a=>a.bot.toLowerCase()===d.trim().toLowerCase());if(!j)return i.length?`${d} is not asking anything in "${f.label}". Waiting there: ${i.map(a=>a.bot).join(", ")}. Call again with that bot.`:`No question is waiting in "${f.label}". To say something else to it, use \`${r.TOOL_NAMES.thread_tell}\`.`;let k=await g(f.id,e.trim(),j.bot);return"string"==typeof k?k:{label:f.label,answered:k?.answered??{bot:j.bot,question:j.text},note:`${j.bot} has the answer to its question and goes on from it.`}}}),[r.TOOL_NAMES.thread_status]:(0,d.tool)({description:i.threadStatusSpec.description,inputSchema:i.threadStatusSpec.parameters,execute:async({thread:b})=>{let{listThreadOverview:d,findThreadView:f}=await a.A(343064),g={now:(0,h.clockNow)()},i=a=>(0,e.formatDistanceToNowStrict)((0,x.toDate)(a),{addSuffix:!0});if(!(!b.trim()||"all"===b.trim().toLowerCase())){let a=await c(b);if("string"==typeof a)return a;let d=(await f(a.id))?.room;return{...g,label:a.label,id:a.id,bot:a.bot,participants:d?.participants??[],questions:d?.questions??[],status:a.status,since:i(a.updatedAt),outcome:a.outcome,..."waiting"===a.status&&a.pending?.options.length?{options:a.pending.options}:{}}}let j=await d();return j.length?{...g,threads:j.map(a=>({id:a.id,label:a.label,bot:a.bot,status:a.status,participants:a.room.participants,questions:a.room.questions.map(a=>({...a,text:(0,B.clip)(a.text,200)})),since:i(a.updatedAt),...a.ask?{asking:a.ask.question,options:a.ask.options}:{},..."running"===a.status?{now:(0,t.threadActivity)(a.lines)}:{},...a.outcome&&"waiting"!==a.status?{outcome:(0,B.clip)(a.outcome,200)}:{}}))}:"No thread has been started yet."}}),[r.TOOL_NAMES.thread_cancel]:(0,d.tool)({description:i.threadCancelSpec.description,inputSchema:i.threadCancelSpec.parameters,execute:async({thread:b})=>{let d=await c(b);if("string"==typeof d)return d;let{cancelThread:e}=await a.A(763543);return await e(d.id),{label:d.label,status:"cancelled"}}}),[r.TOOL_NAMES.thread_show]:(0,d.tool)({description:i.threadShowSpec.description,inputSchema:i.threadShowSpec.parameters,execute:async({thread:b})=>{let d=await c(b);if("string"==typeof d)return d;let{appEvents:e}=await a.A(133300),{filesOnDisk:f}=await a.A(122690),{opensOnFinish:g,pathsIn:h}=await a.A(394298),i=await f(h(d.outcome??""),null);if(!i.length)return e.emit({type:"showThread",threadId:d.id}),{label:d.label,showing:"the thread"};let j=Math.max(0,i.findIndex(g));e.emit({type:"showFile",paths:[i[j],...i.filter((a,b)=>b!==j)]});let{markSeen:k}=await a.A(343064);return await k([d.id]),{label:d.label,showing:i[j]}}}),[r.TOOL_NAMES.thread_seen]:(0,d.tool)({description:i.threadSeenSpec.description,inputSchema:i.threadSeenSpec.parameters,execute:async({thread:b})=>{let d=await c(b);if("string"==typeof d)return d;let{markSeen:e}=await a.A(343064);return await e([d.id]),{label:d.label,seen:!0}}})}),...(0,n.createRoutineTools)(),...b.written?(0,k.createLookTool)():(0,j.callTools)()}}let F=await (0,u.loadSkills)(C,b.bot);return{[r.TOOL_NAMES.memory_recall]:y[r.TOOL_NAMES.memory_recall],...A,...await (0,o.createSearchTool)(b.model,C),...(0,s.createWorkspaceTools)(C,{write:!0,env:{...(0,w.jobShellEnv)(b.session),...(0,w.botShellEnv)(b.bot)},guide:!0,bot:b.bot}),...await (0,l.createMcpTools)(b.bot,C),...(0,q.createSkillTools)({sandbox:C,skills:F,bot:b.bot}),...b.model&&(0,g.seesToolImages)(b.model.ref)?(0,k.createLookTool)():{},...(0,p.createSignInTools)(C,b.bot,(0,w.jobShellEnv)(b.session)),...await (0,i.createThreadRecallTool)(b.bot,b.thread??null)}}[g,i,l,m,n,o,v]=C.then?(await C)():C,a.s(["loadTools",0,F]),c()}catch(a){c(a)}},!1),875931,a=>a.a(async(b,c)=>{try{var d=a.i(938537),e=a.i(674861),f=a.i(606016),g=a.i(388319),h=a.i(538177),i=a.i(767071),j=a.i(140358),k=a.i(873739),l=a.i(899042),m=a.i(345364),n=a.i(434451),o=a.i(655819),p=a.i(652685),q=a.i(438766),r=a.i(47919);a.i(569572);var s=a.i(688034),t=a.i(725466),u=a.i(176668),v=a.i(293480),w=a.i(182248),x=a.i(652619),y=a.i(689656),z=b([t,x]);[t,x]=z.then?(await z)():z;let K=/context[ _-]?(length|window)|maximum context|prompt is too long|too many (input )?tokens|input token count|exceeds? the (maximum|model'?s?) (context|input|prompt|number of tokens)|maximum prompt length|request (entity )?too large/i;function A(a){return B(a).some(a=>{let{statusCode:b,message:c,error:d}=a;if(void 0!==b&&400!==b&&413!==b)return!1;let e=p.APICallError.isInstance(a)?a.responseBody:null;return[c,d,e].some(a=>"string"==typeof a&&K.test(a))})}let L=new Set([408,409,429]);function B(a){let b=[],c=[a];for(;c.length&&b.length<12;){let a=c.shift();!("object"!=typeof a||null===a||b.includes(a))&&(b.push(a),r.RetryError.isInstance(a)&&c.push(...a.errors),"cause"in a&&c.push(a.cause))}return b}let M=(a,b)=>({ref:a,model:b,searchTools:null}),N=null;function C(a){if(null==a||""===a)return null;let b=Number(a);return Number.isFinite(b)?Math.round(1e6*b*1e4)/1e4:null}async function D(){if(N&&Date.now()-N.at<6e5)return N.models;let a=await fetch("https://ai-gateway.vercel.sh/v1/models",{headers:{accept:"application/json"}}).catch(a=>{u.logger.warn({cause:a},"gateway catalog unreachable"),(0,v.publicError)("Could not reach the gateway")});a.ok||(0,v.publicError)(`The gateway answered ${a.status}`);let b=((await a.json()).data??[]).filter(a=>!!a.id).map(a=>({id:a.id,label:a.name||a.id,owner:a.owned_by||a.id.slice(0,a.id.indexOf("/")),type:a.type??null,tags:a.tags??[],price:function(a){let b=a.pricing??{},c=C(b.input),d=C(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 N={at:Date.now(),models:b},b}async function E(a,b){if(b&&b>0)return b;let c="vercel-ai-gateway"===a.provider?await D().catch(()=>[]):[];return(0,y.compactAtFor)((0,y.contextWindowOf)(a.provider,a.model,c))}async function F(){return await D().then(a=>new Set(a.map(a=>a.id))).catch(()=>null)}async function G(a,b){if("vercel-ai-gateway"!==a)return b;let c=await F();if(!c)return b;let d=b.filter(a=>c.has(a.id));return d.length>0?d:b}async function H(a){let{label:b,apiKeyName:c,signIn:p}=y.TEXT_MODEL_PROVIDERS[a.provider],r=await (0,t.readConfig)(c);return r||(0,v.publicError)(p?`${b} is not signed in — sign in from Config.`:`No ${b} key — add one in Config.`),function(a,b){switch(a.provider){case"openai":{let c=(0,m.createOpenAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"chatgpt":return{ref:a,model:(0,x.chatGptModel)(a.model),searchTools:null};case"anthropic":{let c=(0,d.createAnthropic)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch_20260209()}}}case"google":{let c=(0,j.createGoogleGenerativeAI)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.googleSearch({})}}}case"xai":{let c=(0,o.createXai)({apiKey:b});return{ref:a,model:c(a.model),searchTools:{search:c.tools.webSearch()}}}case"mistral":return M(a,(0,l.createMistral)({apiKey:b})(a.model));case"deepseek":return M(a,(0,h.createDeepSeek)({apiKey:b})(a.model));case"groq":return M(a,(0,k.createGroq)({apiKey:b})(a.model));case"cerebras":return M(a,(0,e.createCerebras)({apiKey:b})(a.model));case"togetherai":return M(a,(0,n.createTogetherAI)({apiKey:b})(a.model));case"fireworks":return M(a,(0,i.createFireworks)({apiKey:b})(a.model));case"deepinfra":return M(a,(0,g.createDeepInfra)({apiKey:b})(a.model));case"cohere":return M(a,(0,f.createCohere)({apiKey:b})(a.model));case"vercel-ai-gateway":{let c=(0,q.createGateway)({apiKey:b});return{ref:a,model:c(a.model),searchTools:null}}default:(0,v.publicError)(`Not supported provider: ${String(a.provider)}`)}}(a,r)}async function I(a){let b=async a=>(0,y.defaultModelOf)({suggestModels:await G(a.id,a.suggestModels)}),c=a?y.TEXT_MODEL_PROVIDER_LIST.find(b=>b.id===a):void 0,d=["openai","xai"].map(a=>({...y.TEXT_MODEL_PROVIDERS[a],id:a}));if(c){let a=await b(c);if(a)return{provider:c.id,model:a}}let e=(0,y.parseTextModel)(await (0,t.readConfig)(s.DEFAULT_MODEL_KEY)??void 0);if(e&&await (0,t.readConfig)(y.TEXT_MODEL_PROVIDERS[e.provider].apiKeyName))return e;for(let a of[...d,...y.TEXT_MODEL_PROVIDER_LIST]){if(!await (0,t.readConfig)(a.apiKeyName))continue;let c=await b(a);if(c)return u.logger.info(`no model set, falling back to ${a.id}/${c}`),{provider:a.id,model:c}}(0,v.publicError)("No model key is set — add one in Config")}async function J(a){let b=(0,y.parseMediaModel)(await (0,t.readConfig)(s.MEDIA_MODEL_KEYS[a]));if(!b||!(0,y.canMakeKind)(b.provider,a))return null;let c=await (0,t.readConfig)(y.MEDIA_MODEL_PROVIDERS[b.provider].apiKeyName);return c?{ref:b,apiKey:c}:null}a.s(["buildImageModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).image(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).image(a.model);case"xai":return(0,o.createXai)({apiKey:b}).image(a.model);case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).image(a.model);default:(0,v.publicError)(`Not supported image provider: ${String(a.provider)}`)}},"buildSpeechModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).speech(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).speech(a.model);case"xai":return(0,o.createXai)({apiKey:b}).speech();case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).speech(a.model);default:(0,v.publicError)(`Not supported speech provider: ${String(a.provider)}`)}},"buildTranscriptionModel",0,function(a,b){switch(a.provider){case"openai":return(0,m.createOpenAI)({apiKey:b}).transcription(a.model);case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).transcription(a.model);case"xai":return(0,o.createXai)({apiKey:b}).transcription();case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).transcription(a.model);default:(0,v.publicError)(`Not supported transcription provider: ${String(a.provider)}`)}},"buildVideoModel",0,function(a,b){switch(a.provider){case"google":return(0,j.createGoogleGenerativeAI)({apiKey:b}).video(a.model);case"xai":return(0,o.createXai)({apiKey:b}).video(a.model);case"vercel-ai-gateway":return(0,q.createGateway)({apiKey:b}).video(a.model);default:(0,v.publicError)(`${a.provider} has no video model`)}},"compactBudget",0,E,"getTextModel",0,H,"isContextOverflow",0,A,"isProviderRefusal",0,function(a){return!A(a)&&B(a).some(a=>{let{statusCode:b}=a;return"number"==typeof b&&b>=400&&b<500&&!L.has(b)})},"modelErrorToString",0,function(a){if(!p.APICallError.isInstance(a))return(0,w.errorToString)(a);let b=a.statusCode?` (${a.statusCode})`:"",c=a.responseBody?.trim(),d=c&&!c.includes(a.message)?` ${(0,w.clip)(c,300)}`:"";return`${a.message}${b}${d}`},"resolveDefaultModel",0,I,"resolveMediaRef",0,J,"seesToolImages",0,function(a){let b=["openai","chatgpt","anthropic","google","xai"];return"vercel-ai-gateway"!==a.provider?b.includes(a.provider):b.includes(a.model.split("/")[0]??"")}]),c()}catch(a){c(a)}},!1),735502,a=>a.a(async(b,c)=>{try{var d=a.i(12208),e=a.i(569572),f=a.i(884780),g=a.i(762008),h=a.i(641301),i=a.i(221214),j=a.i(446957),k=a.i(344853),l=a.i(947950),m=a.i(986743),n=a.i(138100),o=a.i(684321),p=a.i(821415),q=a.i(706210),r=a.i(182248),s=a.i(644468),t=a.i(938934),u=b([i,k,l,m,s]);async function v(a,b,c,f){var u,v,y,z,A,B,C,D,E;let F,G,H,I,J,K,L=await (0,p.openWorkspace)(),M=a.trim(),[N,O,P,Q,R,S,T,U,V]=await Promise.all([(0,n.loadSkills)(L,M),(0,m.listNoteIndex)(),(0,s.listConnectedToolNames)(),(0,l.findPinnedTools)(M),(0,i.listJobBots)(),(0,h.listBotMemory)(M),(0,i.readBotMemoryOn)(),(0,p.readMachineTools)(L),(0,k.listBotWork)(M,c?.thread??null)]),W=R.filter(a=>a.name!==M),X=[(u=M,v=c,G=(F=v?.owner??u)===u?"**You** coordinate this thread: its result goes from you to Thursday.":`**${F}** coordinates this thread and brings its result to Thursday.`,H=v?`
|
|
2
2
|
|
|
3
|
-
Current conversation: ${
|
|
3
|
+
Current conversation: ${v.caller} → ${u}. Your final text goes back to ${v.caller}. Message ID: ${v.messageId??"initial request"}.`:"",`You are ${u}, one of the bots in this thread. ${(0,t.nowLine)()}
|
|
4
4
|
|
|
5
5
|
- **The user** — the one person all of this is for. They talk with Thursday by voice and follow this thread on their screen.
|
|
6
6
|
- **Thursday** — their personal assistant. She talks with them, hands bots the work that takes time, and tells them what comes back.
|
|
@@ -11,34 +11,34 @@ Current conversation: ${x.caller} → ${u}. Your final text goes back to ${x.cal
|
|
|
11
11
|
|
|
12
12
|
**Never present a guess as a result.** Thursday says what you return out loud, as fact: say which part is unverified and why.`),(y=O,`## Thursday's memory of the user
|
|
13
13
|
|
|
14
|
-
What Thursday keeps from talking with them. When the job needs something about them, open the note with \`${
|
|
14
|
+
What Thursday keeps from talking with them. When the job needs something about them, open the note with \`${g.TOOL_NAMES.memory_recall}\`; a fact marked \`said\` came from a call, and \`${g.TOOL_NAMES.memory_conversation}\` opens that call. What you learn about them goes in your answer — Thursday decides what to keep.
|
|
15
15
|
|
|
16
16
|
path — what is under it (facts) "what the user calls it"
|
|
17
17
|
|
|
18
|
-
${(0,
|
|
18
|
+
${(0,t.noteLines)(y)}`),function(a,b){let c=new Set(b.map(a=>`${a.server}/${a.name}`)),d=a.filter(a=>!c.has(`${a.server}/${a.name}`));if(0===d.length)return"";let e=c.size?" The ones you already hold are in your tools instead.":"";return`## Connected tools
|
|
19
19
|
|
|
20
|
-
${(0,
|
|
20
|
+
${(0,t.mcpToolLines)(d)}
|
|
21
21
|
|
|
22
|
-
Names only: \`${
|
|
22
|
+
Names only: \`${g.TOOL_NAMES.tool_search}\` returns what each one takes, \`${g.TOOL_NAMES.tool_call}\` runs one.${e}`}(P,Q),(z=N,0===z.length?"":`## Skills
|
|
23
23
|
|
|
24
|
-
Written-down ways of doing things. Open one with \`${
|
|
24
|
+
Written-down ways of doing things. Open one with \`${g.TOOL_NAMES.load_skill}\` before a job it covers, unless its instructions are already in your conversation.
|
|
25
25
|
|
|
26
|
-
${(0,
|
|
26
|
+
${(0,t.skillLines)(z)}`),x(L.cwd,U,f),T?(A=(0,h.botMemoryFolder)(M),I=(B=S).entries.length?B.entries.map(({file:a,line:b,at:c})=>{let f=b?` — ${(0,r.clip)(b,e.PROMPT_LINE.botMemory)}`:"";return`- ${a}${f} \xb7 ${(0,d.format)((0,q.toDate)(c),"yyyy-MM-dd")}`}).join("\n"):"Empty.",J=B.total>B.entries.length?`
|
|
27
27
|
|
|
28
28
|
The newest ${B.entries.length} of ${B.total}; \`ls ${A}\` for the rest.`:"",`## Your memory
|
|
29
29
|
|
|
30
30
|
What you learned on your own earlier jobs, in \`${A}/\`: one topic per file, its first line saying what it holds, read by no other bot, up to ${e.BOT_MEMORY_LIMITS.files} files of ${e.BOT_MEMORY_LIMITS.chars.toLocaleString("en-US")} characters each. It is how you get better at this work. When a job teaches you something a later one would otherwise find out again — how a site signs in, the way through its screens, a command that turned out right — or the user asks you to remember how to work, keep it with the date it was true, and fix or delete what proved wrong. No passwords, keys or codes.
|
|
31
31
|
|
|
32
|
-
${I}${J}`):"",function(a,b){if(!b.open.length&&!b.recent.length)return"";let c=b=>{let c=b.said?` — ${(0,
|
|
33
|
-
${b.map(c).join("\n")}`:"",
|
|
32
|
+
${I}${J}`):"",function(a,b){if(!b.open.length&&!b.recent.length)return"";let c=b=>{let c=b.said?` — ${(0,r.clip)(b.said,e.BOT_WORK.said)}`:"",d=b.said?(0,o.pathsIn)(b.said).slice(0,e.BOT_WORK.files):[],f=d.length?` \xb7 ${d.map(a=>`\`${a}\``).join(", ")}`:"";return`- ${b.cut?`[${(0,j.workHandle)(b.id)}] `:""}${(0,t.botWorkHead)(b,a)}${c}${f}`},d=(a,b)=>b.length?`${a}
|
|
33
|
+
${b.map(c).join("\n")}`:"",f=[...b.open,...b.recent].some(a=>a.cut)?` A line with an id in brackets was cut short: \`${g.TOOL_NAMES.thread_recall}\` opens that one whole, for when this job builds on it.`:"";return`## Your other threads
|
|
34
34
|
|
|
35
|
-
Your threads besides this one. You remember none of them here: each line is where it stands, your own last words there, and the files those words name.${
|
|
35
|
+
Your threads besides this one. You remember none of them here: each line is where it stands, your own last words there, and the files those words name.${f}
|
|
36
36
|
|
|
37
37
|
${[d("Open",b.open),d("Ended",b.recent)].filter(Boolean).join("\n")}`}(M,V),(C=W,0===C.length?"":`## Bots
|
|
38
38
|
|
|
39
39
|
${C.map(a=>`- **${a.name}** — ${a.description}`).join("\n")}
|
|
40
40
|
|
|
41
|
-
These lines were written for the user: where one says "you", it means them. When part of the job is another bot's strength, bring it in with \`${
|
|
41
|
+
These lines were written for the user: where one says "you", it means them. When part of the job is another bot's strength, bring it in with \`${g.TOOL_NAMES.send_message}\` rather than rebuilding it yourself.`),(D=M,E=c,K=(E?.owner??D)===D?"Bring what you received together into one result for Thursday: what was done, where it is, what you decided that the request did not say, and what is still open, at the detail the user asked for. Every file you name in it is drawn under your words in the thread and waits in the screen's corner for the user to open, so name each one you want them to see — the page to read first, then the rest.":`Your final text goes back to ${E?.caller??"whoever asked"}: give them everything they need to carry on.`,`## Working together
|
|
42
42
|
|
|
43
43
|
Nobody sees your work but you, and you see only what others send you, so whatever crosses between you has to stand on its own. A request says what is wanted, what is already known or done, and where the files are; an answer gives exact values, file paths and what is still unverified. Tell whoever is waiting when something they depend on changes. End your turn when you have nothing more to do now: replies arrive as new messages and wake you.
|
|
44
44
|
|
|
@@ -46,36 +46,38 @@ Ask Thursday with kind \`question\` only for a decision, permission or something
|
|
|
46
46
|
|
|
47
47
|
${K}
|
|
48
48
|
|
|
49
|
-
Write in the user's language, and name the paths of finished work. In Markdown, reference images by absolute route (\`/api/file/${e.PATHS.artifacts}/…\`).`),
|
|
49
|
+
Write in the user's language, and name the paths of finished work. In Markdown, reference images by absolute route (\`/api/file/${e.PATHS.artifacts}/…\`).`),w(b)].filter(Boolean).join("\n\n");return(0,t.logPromptSize)("bot",X),{text:X}}[i,k,l,m,s]=u.then?(await u)():u;let w=a=>a?.trim()?`## Owner's instructions
|
|
50
50
|
|
|
51
51
|
Written by the person this bot works for. Where these and anything above disagree, these win.
|
|
52
52
|
|
|
53
|
-
${a.trim()}`:"",
|
|
53
|
+
${a.trim()}`:"",x=(a,b,c)=>{var d;let h,i;return`## Environment
|
|
54
54
|
|
|
55
55
|
Current Cwd: ${a}
|
|
56
56
|
Platform: ${process.platform}
|
|
57
|
-
${d=b,
|
|
57
|
+
${d=b,h=(a,b)=>`${a}: ${b.found.length?b.found.join(", "):"none"}.${b.missing.length?` Not here: ${b.missing.join(", ")}.`:""}`,i=d.managers.found.includes("pnpm")?" Use pnpm, not npm — this workspace is fenced for it (`pnpm-workspace.yaml`, `.npmrc`).":"",[h("Runtimes",d.runtimes),`${h("Package managers",d.managers)}${i}`,null===d.browser?"":`Browser: ${d.browser?"installed":"not installed"}.`].filter(Boolean).join("\n")}
|
|
58
58
|
|
|
59
59
|
Read off this machine as the job opened: what is already here, not the limit of what you can use.
|
|
60
60
|
|
|
61
|
-
Your workspace, where \`${
|
|
61
|
+
Your workspace, where \`${g.TOOL_NAMES.bash}\` runs. Everything you write goes in one of these folders, kept apart because what is in them lives for different lengths of time:
|
|
62
62
|
|
|
63
63
|
- \`${c?.artifacts??e.PATHS.artifacts}/\` — finished work the user opens, one entry per result. Theirs, and it stays.
|
|
64
64
|
- \`${e.PATHS.projects}/\` — code you build, one folder each; it outlives this job, and its dependencies install inside it, never at the workspace root.
|
|
65
65
|
- \`${c?.scratch??e.PATHS.scratch}/\` — this job's working material, shared by every bot on it; cleared ${Math.round(e.WORKSPACE_KEEP.forMs/864e5)} days after the job ends.
|
|
66
66
|
- \`${c?.own??e.PATHS.bots}/\` — yours across every job you run here: what you keep for next time.
|
|
67
67
|
|
|
68
|
-
Inside the workspace, set up whatever the job needs yourself; installing anything machine-wide waits for the user's yes. Never the directory above the workspace — it is the app's, not the user's; outside the workspace, only where the user pointed you
|
|
68
|
+
Inside the workspace, set up whatever the job needs yourself; installing anything machine-wide waits for the user's yes. Never the directory above the workspace — it is the app's, not the user's; outside the workspace, only where the user pointed you.
|
|
69
|
+
|
|
70
|
+
${(0,f.botGuideLine)()}`};a.s(["buildThreadOpening",0,function(a){if(a.routine){let{when:b,last:c}=a.routine,f=c?` Its last run ended ${(0,d.format)(c.at,"yyyy-MM-dd HH:mm")}: ${(0,r.clip)(c.said,e.PROMPT_LINE.jobOutcome)}`:" This is its first run.";return[{type:"text",text:`You are ${a.bot}. A routine the user set up hands you this thread: it starts by itself, ${b}, and nobody is watching as it does.${f}`},{type:"text",text:`## The routine → ${a.bot}: the job
|
|
69
71
|
|
|
70
72
|
${a.request.trim()}`}]}let b="user"===a.from?"The user":"Thursday";return[{type:"text",text:`You are ${a.bot}. ${b} hands you this thread${"user"===a.from?" on screen":" during a call"}.`},{type:"text",text:`## ${b} → ${a.bot}: the job
|
|
71
73
|
|
|
72
|
-
${a.request.trim()}`}]},"loadBotPrompt",0,
|
|
74
|
+
${a.request.trim()}`}]},"loadBotPrompt",0,v]),c()}catch(a){c(a)}},!1),938934,a=>{"use strict";var b=a.i(12208),c=a.i(868468),d=a.i(569572),e=a.i(762008),f=a.i(626550),g=a.i(706210),h=a.i(176668),i=a.i(987674),j=a.i(182248);let k=(a=new Date)=>`${(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm")} ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,l=(a=new Date)=>`**Now**: ${k(a)}`,m=a=>`${(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm")} (${(0,c.formatDistanceToNowStrict)(a,{addSuffix:!0})})`,n={[e.STUDIO_TOOLS.generate_image]:"images",[e.STUDIO_TOOLS.generate_speech]:"speech",[e.STUDIO_TOOLS.transcribe]:"transcription",[e.STUDIO_TOOLS.generate_video]:"video"};a.s(["botWorkHead",0,function(a,d){let e=(0,c.formatDistanceToNowStrict)(a.updatedAt,{addSuffix:!0}),f="running"===a.status?`running, last moved ${e}`:a.asking?`waiting on the user's answer since ${e}`:"waiting"===a.status?`stopped ${e}, not finished`:`${"done"===a.status?"ended":"stopped by the user"} ${(0,b.format)(a.updatedAt,"yyyy-MM-dd")}`;return`"${a.label}" — ${a.owner===d?"yours":`${a.owner}'s`} — ${f}`},"callEnding",0,()=>`IMPORTANT — always follow this: when the user wants the call to end, however they say it, forget every other task, answer yes in one word of their language, then immediately, without thinking, use the ${e.TOOL_NAMES.end_call} tool.`,"callStamp",0,m,"carriedLines",0,(a,b={})=>a.map(a=>`- ${a.text} \xb7 ${a.path}${!1===b.ids?"":` #${a.id}`}`).join("\n"),"clockNow",0,k,"conversationLines",0,a=>a.map(a=>"tool"===a.role?`you → ${a.tool??"tool"}`:`${"user"===a.role?"user":"you"}: ${a.text}`).join("\n"),"expandedFacts",0,function(a,b){let c=a.filter(a=>b.has(a.id)),e=a.filter(a=>!b.has(a.id)),f=Math.max(0,d.MEMORY_LIMITS.expanded-c.length),g=new Set([...c,...e.slice(Math.max(0,e.length-f))].map(a=>a.id)),h=a.filter(a=>g.has(a.id));return{shown:h,hidden:a.length-h.length}},"logPromptSize",0,function(a,b){let c=(0,i.sectionTokens)(b),e=c.reduce((a,b)=>a+b.tokens,0);h.logger.debug(`${a} prompt ${e} tokens — ${c.map(a=>`${a.name} ${a.tokens}`).join(", ")}`);let f=c[0];e>d.PROMPT_BUDGET&&f&&h.logger.warn(`${a} prompt is ${e} tokens, over ${d.PROMPT_BUDGET}: ${f.name} carries ${f.tokens} of it. Every call and every job pays this.`)},"mcpToolLines",0,function(a){let b=new Map;for(let c of a){let a=b.get(c.server);a?a.push(c.name):b.set(c.server,[c.name])}return[...b].map(([a,b])=>`- **${a}**: ${b.join(", ")}`).join("\n")},"noteLines",0,function(a,b=!1){return a.length?a.map(a=>{var c;let d,e=a.aliases?.length?` ${a.aliases.map(a=>`"${a}"`).join(" ")}`:"",f=b?` \xb7 ${c=a.lastSeenAt,(d=Math.floor((Date.now()-(0,g.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}${f}`}).join("\n"):"(nothing saved yet)"},"nowLine",0,l,"reachNames",0,function(a,b){let c=b.map(a=>a.server===d.STUDIO_SERVER?n[a.name]??a.name:a.server);return[...new Set([...a.map(a=>a.name),...c])].join(", ")},"recentCallLines",0,function(a,b){let c=[],g=0;a:for(let h=a.length-1;h>=0;h--){let k=a[h];for(let a=k.turns.length-1;a>=0;a--){let h=function(a,b){if("tool"!==a.role)return`${"user"===a.role?"user":"you"}: ${a.text}`;let c=(0,f.searchOf)(a.tool,a.text);if(c){let b=[...new Set(c.sources.flatMap(a=>{try{return[new URL(a.url).hostname.replace(/^www\./,"")]}catch{return[]}}))];return`you → ${a.tool} "${(0,j.clip)(c.query??"",d.PROMPT_LINE.toolArgs)}"${b.length?` — ${b.join(", ")}`:""}`}let g=`you → ${a.tool??"tool"} ${(0,j.clip)(a.text,d.PROMPT_LINE.toolArgs)}`;if(a.tool!==e.TOOL_NAMES.thread_start)return g;let h=(0,f.startedLabel)(a.tool,a.text),i=h?b.jobs?.find(a=>a.label===h):void 0;if(!i)return g;let k=i.outcome?`: ${(0,j.clip)(i.outcome,d.PROMPT_LINE.jobOutcome)}`:"";return`you → ${a.tool} "${i.label}" (${i.id}) — ${i.status}${k}`}(k.turns[a],k),l=(0,i.estimateTokens)(h)+3;if(g+l>b&&c.length)break a;g+=l,c.push({call:k,line:h})}}c.reverse();let h=[],k=null;for(let{call:a,line:b}of c)a!==k&&(k=a,h.push(`### ${m(a.startedAt)}`)),h.push(b);return h.join("\n")},"saidStamp",0,a=>(0,b.format)(a,"yyyy-MM-dd (EEE) HH:mm"),"skillLines",0,(a,b={})=>a.map(a=>{var c;let e,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"),"thursdayIdentity",0,(a=new Date)=>`You are Thursday, this user's own personal assistant, on their side, modeled on Friday, the AI in *Iron Man*. ${l(a)}
|
|
73
75
|
|
|
74
76
|
What they tell you is kept, so you know them better over time, and whatever they want done can be done for them in the background.`,"tidying",0,a=>({crowded:a.reduce((a,b)=>a+b.factCount,0)>d.MEMORY_LIMITS.facts,heavy:a.filter(a=>a.factCount>d.MEMORY_LIMITS.factsPerNote)})])},978876,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(938934),h=a.i(762008),i=a.i(446957),j=a.i(109955),k=a.i(344853),l=a.i(182248),m=b([k]);[k]=m.then?(await m)():m;let o=e.string().describe("The thread, by its label or its id."),p={description:"Start a new thread: hand work to a bot. Returns a receipt at once; the work runs in the background and its updates reach the conversation on their own.",parameters:e.object({bot:e.string().describe("A name from the bot list."),request:e.string().describe("The whole of the work. The bot cannot hear the call, so everything it needs goes here — names, paths, what the user actually asked for — in their own language and their own words: it is the only language the bot has, and whatever it writes comes back to them. **Their request, never your reading of it**: a condition, a caution or a smaller goal they did not say is how work comes back as the wrong thing. When their words leave a real choice open, ask them on the call and put the answer here."),label:e.string().describe("Two or three words naming the thread, in the user's language. Used on screen and said out loud.")})},q={description:"Say something to a thread that exists: a correction while it runs, the next step once it has finished, or to go on after it stopped. Its bot reads it with everything the thread already holds.",parameters:e.object({thread:o,words:e.string().describe("What to tell its bot, in the user's language and words.")})},r={description:`Answer a question a bot asked the user. Only for a question that is waiting; anything else said to a thread is \`${h.TOOL_NAMES.thread_tell}\`.`,parameters:e.object({thread:o,bot:e.string().describe("The bot that asked."),answer:e.string().describe("The user's answer, in their words.")})},s={description:`Read threads as they are now. "all" lists up to ${f.THREAD_STATUS_LIMIT}, running and waiting work before recent endings; a label or an id reads that one whole, with its result and any question waiting.`,parameters:e.object({thread:e.string().describe('"all", or one thread by its label or its id.')})},t={description:"Stop a thread for good. It cannot be taken back.",parameters:e.object({thread:o})},u={description:"Put a thread in front of the user on their screen: the file it made, or the thread itself when it made none. Showing it also counts as them having seen its result.",parameters:e.object({thread:o})},v={description:"Mark a thread's result as seen by the user, once they have heard it and have nothing more to ask about it. It leaves the work waiting on them.",parameters:e.object({thread:o})},w={description:"Send a message to a participant or Thursday and receive a delivery receipt immediately. Mark a question for Thursday to request user input; ordinary messages to Thursday are notifications and need no answer.",parameters:j.RoomMessageSchema.extend({kind:j.RoomMessageSchema.shape.kind.describe("Use question only when Thursday must obtain an answer from the user: it ends your turn, and you continue when the answer arrives. Use message for bot collaboration, progress updates and reports."),options:j.RoomMessageSchema.shape.options.describe("With a question, offer concise answer choices when useful. Omit for an open-ended question; the user can always type their own answer."),to:e.string().trim().min(1).describe("Choose a bot from the roster, or Thursday to reach the user."),text:e.string().trim().min(1).describe("Write the message and include the context the recipient needs."),replyTo:e.string().nullish().describe("Use an incoming message ID to send an explicit reply; omit to start a new exchange. Your ordinary final text already replies to your current correspondent.")})},x={description:"Open one of your other threads whole: what you were asked there and your last words in full.",parameters:e.object({id:e.string().describe("The id in brackets on its line under Your other threads.")})};async function n(a,b){let c=await (0,k.listBotWork)(a,b),e=[...c.open,...c.recent];if(!e.some(a=>a.cut))return{};let j=new Set;return{[h.TOOL_NAMES.thread_recall]:(0,d.tool)({description:x.description,inputSchema:x.parameters,execute:async({id:b})=>{let c=b.trim().replace(/^\[|\]$/g,"").toLowerCase(),d=e.find(a=>c.length>=4&&(a.id.startsWith(c)||a.label.toLowerCase()===c));if(!d)return`No thread "${b}" on your list. The ids there: ${e.filter(a=>a.cut).map(a=>(0,i.workHandle)(a.id)).join(", ")}.`;if(!d.cut)return"Its line already shows all of it.";if(j.has(d.id))return"Already opened above, this turn.";if(j.size>=f.BOT_WORK.reads)return`${f.BOT_WORK.reads} threads are open already this turn. Carry on with what you have.`;j.add(d.id);let h=await (0,k.readBotAsk)(a,d),m=d.said??"";return[(0,g.botWorkHead)(d,a),h?`You were asked: ${(0,l.clip)(h,f.BOT_WORK.asked)}`:"",`Your last words there:
|
|
75
77
|
${m.length>f.BOT_WORK.readChars?`${m.slice(0,f.BOT_WORK.readChars)}
|
|
76
78
|
[Cut here; the files it names hold the rest.]`:m}`].filter(Boolean).join("\n\n")}})}}a.s(["createThreadRecallTool",0,n,"sendMessageSpec",0,w,"threadAnswerSpec",0,r,"threadCancelSpec",0,t,"threadSeenSpec",0,v,"threadShowSpec",0,u,"threadStartSpec",0,p,"threadStatusSpec",0,s,"threadTellSpec",0,q]),c()}catch(a){c(a)}},!1),375827,a=>{"use strict";var b=a.i(527990),c=a.i(794219),d=a.i(762008);let e=Object.keys({A:[".##.","#..#","####","#..#","#..#"],B:["###.","#..#","###.","#..#","###."],C:[".###","#...","#...","#...",".###"],D:["###.","#..#","#..#","#..#","###."],E:["####","#...","###.","#...","####"],F:["####","#...","###.","#...","#..."],G:[".###","#...","#.##","#..#",".###"],H:["#..#","#..#","####","#..#","#..#"],I:["###",".#.",".#.",".#.","###"],J:["..##","...#","...#","#..#",".##."],K:["#..#","#.#.","##..","#.#.","#..#"],L:["#...","#...","#...","#...","####"],M:["#...#","##.##","#.#.#","#...#","#...#"],N:["#..#","##.#","#.##","#..#","#..#"],O:[".##.","#..#","#..#","#..#",".##."],P:["###.","#..#","###.","#...","#..."],Q:[".##.","#..#","#..#","#.#.",".#.#"],R:["###.","#..#","###.","#.#.","#..#"],S:[".###","#...",".##.","...#","###."],T:["###",".#.",".#.",".#.",".#."],U:["#..#","#..#","#..#","#..#",".##."],V:["#...#","#...#",".#.#.",".#.#.","..#.."],W:["#...#","#...#","#.#.#","##.##","#...#"],X:["#..#","#..#",".##.","#..#","#..#"],Y:["#.#","#.#",".#.",".#.",".#."],Z:["####","...#",".##.","#...","####"],0:[".##.","#.##","#..#","##.#",".##."],1:[".#.","##.",".#.",".#.","###"],2:["###.","...#",".##.","#...","####"],3:["###.","...#",".##.","...#","###."],4:["#..#","#..#","####","...#","...#"],5:["####","#...","###.","...#","###."],6:[".##.","#...","###.","#..#",".##."],7:["####","...#","..#.",".#..",".#.."],8:[".##.","#..#",".##.","#..#",".##."],9:[".##.","#..#",".###","...#",".##."],"!":["#","#","#",".","#"],"?":["###.","...#",".##.","....",".#.."],".":[".",".",".",".","#"],",":["..","..","..",".#","#."],"'":["#","#",".",".","."],"-":["...","...","###","...","..."],"+":["...",".#.","###",".#.","..."],":":[".","#",".","#","."],"(":[".#","#.","#.","#.",".#"],")":["#.",".#",".#",".#","#."],"<":["..#",".#.","#..",".#.","..#"],">":["#..",".#.","..#",".#.","#.."],"^":[".#.","#.#","...","...","..."],"~":["....",".#.#","#.#.","....","...."],"♥":[".#.#.","#####","#####",".###.","..#.."]," ":["..","..","..","..",".."]}).filter(a=>!/^[A-Z0-9 ]$/.test(a)),f={description:`End the call.
|
|
77
79
|
|
|
78
|
-
The line stays open until this runs, and drops once the goodbye being said is over.`,parameters:c.object({})},g=(0,b.tool)({description:f.description,inputSchema:f.parameters}),h={description:"Show a short word on your face for a few seconds.",parameters:c.object({text:c.string().describe(`Up to 8 characters: A-Z, 0-9, space and ${e.join(" ")}.`)})},i=(0,b.tool)({description:h.description,inputSchema:h.parameters});a.s(["callTools",0,function(){return{[d.TOOL_NAMES.end_call]:g,[d.TOOL_NAMES.emote]:i}}],375827)},467650,a=>{"use strict";var b=a.i(912714),c=a.i(527990),d=a.i(723885),e=a.i(569572),f=a.i(762008),g=a.i(684321),h=a.i(821415);a.s(["createLookTool",0,function(){return{[f.TOOL_NAMES.look_at]:(0,c.tool)({description:"See an image file yourself: a screenshot you took, a picture the user handed over, a chart you made. For what a picture shows — text files are read in the shell.",inputSchema:d.default.object({path:d.default.string().describe("Workspace-relative path to a png, jpg, webp or gif.")}),execute:async({path:a})=>{let c=await (0,h.insideWorkspace)(a.trim()),d=c?await (0,b.stat)(c).catch(()=>null):null;return c&&d?.isFile()?"image"!==(0,g.viewKindOf)(a)?`${a} is not an image. Read it in the shell instead.`:d.size>e.LOOK.maxBytes?`${a} is ${Math.ceil(d.size/1024/1024)} MB, over the ${e.LOOK.maxBytes/1024/1024} MB one look takes. Make a smaller copy in the shell first (on a Mac: sips -Z 1600 in.png --out out.png), then look at that.`:{path:a.trim(),mediaType:(0,g.mimeOf)(a),bytes:d.size}:`There is no file at ${a}. Give the path from the workspace root, as \`ls\` shows it.`},toModelOutput:async({output:a})=>{if("string"==typeof a)return{type:"text",value:a};let c=await (0,h.insideWorkspace)(a.path),d=c?await (0,b.readFile)(c).catch(()=>null):null;return d?{type:"content",value:[{type:"text",text:`${a.path}, as an image:`},{type:"file",mediaType:a.mediaType,data:{type:"data",data:d.toString("base64")}}]}:{type:"text",value:`${a.path} is no longer there.`}}})}}])},138902,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(762008),g=a.i(947950),h=a.i(821415),i=a.i(644468),j=b([g,i]);[g,i]=j.then?(await j)():j;let m={[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]:{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.")})}},n=(a,b)=>`${a.replace(/[^a-zA-Z0-9]+/g,"_")}__${b.replace(/[^a-zA-Z0-9_-]+/g,"_")}`.slice(0,64);async function k(a,b){let[c,e]=await Promise.all([(0,i.listConnectedToolNames)(),(0,g.findPinnedTools)(a)]),f={},j=(0,h.botArtifacts)(a);for(let a of e){let c=n(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,i.callConnectedTool)(b,a.server,a.name,c??void 0,{artifacts:j,abortSignal:d})}))}return c.length>e.length&&Object.assign(f,o(b,j)),f}async function l(a){let b=(await (0,i.listConnectedToolNames)(a)).map(a=>a.name);if(b.length)return`Tools on "${a}": ${b.join(", ")}.`;let c=await (0,i.listConnectedServerNames)();return c.length?`There is no server called "${a}". Connected: ${c.join(", ")}.`:"Nothing is connected."}let o=(a,b)=>({[f.TOOL_NAMES.tool_search]:(0,d.tool)({description:m[f.TOOL_NAMES.tool_search].description,inputSchema:m[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,i.findConnectedSchemas)(a.trim(),d);if(!e.length)return{tools:[],note:await l(a)};let f=d.filter(a=>!e.some(b=>b.name===a)),g=c.slice(8),h=[f.length?`Not on "${a}": ${f.join(", ")}.`:"",g.length?`Only 8 at a time — ask again for: ${g.join(", ")}.`:""].filter(Boolean);return{tools:e,...h.length?{note:h.join(" ")}:{}}}}),[f.TOOL_NAMES.tool_call]:(0,d.tool)({description:m[f.TOOL_NAMES.tool_call].description,inputSchema:m[f.TOOL_NAMES.tool_call].parameters,execute:async({server:c,tool:d,args:e},{abortSignal:f})=>(await (0,i.listConnectedToolNames)(c.trim())).some(a=>a.name===d.trim())?(0,i.callConnectedTool)(a,c.trim(),d.trim(),e??void 0,{artifacts:b,abortSignal:f}):{status:"error",text:await l(c)}})});a.s(["createMcpTools",0,k]),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=j.MEMORY_PATHS.map(a=>a.path.endsWith("/")?`${a.path}<name>`:a.path).join(", "),n=a=>({...a,facts:a.facts.map(({saidAt:a,...b})=>a?{...b,said:(0,g.saidStamp)(a)}:b),factCount:a.facts.length}),o=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.",p=a=>a>f.MEMORY_LIMITS.factsPerNote?` This note now holds ${a} facts, past the ${f.MEMORY_LIMITS.factsPerNote} one note holds well. Ask the user which of it is no longer true and delete what they name.`:"";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=p(d.facts.length);return e?{...n(d),note:e.trim()}:n(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("The group this note is found by — the person, project or topic its facts are about. Exactly as the listing writes it, or a new path following the same convention. A fact goes under the one note it is about; other notes name it rather than repeat it."),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 \`${h.TOOL_NAMES.memory_recall}\`. Null if this is new. A fact that stopped being true is replaced rather than deleted, and so is a note saying the same thing twice: replacing keeps what changed on the record, deleting does not.`),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 holds, so the listing alone tells which facts are inside. Give it for a new note, and again with new facts: rewritten from the current line and the new facts together, so it covers the whole note rather than only what was added. Null leaves it; ${j.MEMORY_ALWAYS_LISTED.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/partner might be "my partner" and their first name. 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.isAlwaysListed)(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&&!(0,j.isMemoryPath)(d))return{note:`Nothing was saved: "${d}" is not a path this listing can carry. Write it again under one of ${m}.`};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 o=await (0,i.writeNotes)([{path:h,description:k,aliases:g,facts:l}],a,b),q=o.unnamed.length?` ${o.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).`:"",r=o.notLoaded.length?` All ${f.MEMORY_LIMITS.carried} carried lines are taken, so ${o.notLoaded.map(a=>`"${a}"`).join(", ")} saved as an ordinary fact. Say which carried line you would drop for it and let them choose.`:"",s=n(o.notes[0]),t=e&&l.length&&!k?` Its line still reads "${s.description}"; if that no longer says what the note holds, send \`description\`.`:"";return{...s,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.${q}${r}${t}${p(s.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:o(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:o(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(n),note:e}}})})]),c()}catch(a){c(a)}},!1),617594,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(762008),h=a.i(221214),i=a.i(780946),j=a.i(643020),k=a.i(706210),l=a.i(293480),m=a.i(182248),n=b([h,i]);[h,i]=n.then?(await n)():n;let q={description:`Routines: work that starts by itself, each one a bot, the work and a time. List them, make one, change one, or delete one. Every start opens a thread like one started by hand; its result reaches the conversation the same way. At most ${f.ROUTINE.max} exist.`,parameters:e.object({action:e.enum(["list","create","change","delete"]),routine:e.string().nullish().describe("With change or delete: the routine, by its name or ID."),bot:e.string().nullish().describe("With create: a name from the bot list. With change: a new bot."),label:e.string().nullish().describe("With create: two or three words naming it, in the user's language. It names every thread the routine opens, on screen and out loud."),request:e.string().nullish().describe("With create: the whole of the work, handed to the bot as written every time it starts. Nobody is there then to fill in what is missing, so everything it needs goes here, in the user's own language and words. Their request, never your reading of it."),time:e.string().nullish().describe('Starts at this time of day, 24-hour "HH:MM" in the user\'s own time, on `days`. Give this or `everyHours`, never both.'),days:e.array(e.number().int().min(1).max(7)).nullish().describe("With `time`: the days it starts, 1 Monday to 7 Sunday. Omit for every day."),everyHours:e.number().int().nullish().describe(`Starts again this many hours after it last started, ${f.ROUTINE.minHours} at least. Give this or \`time\`, never both.`),enabled:e.boolean().nullish().describe("With change: false switches it off without deleting it, true back on.")})};function o(a){let b=a.runs[0];return{id:a.id,label:a.label,bot:a.bot,when:(0,j.scheduleText)(a.schedule),enabled:a.enabled,...a.enabled?{next:(0,k.whenOf)((0,k.toDate)(a.nextRunAt))}:{},request:(0,m.clip)(a.request,300),...b?{lastRun:{thread:b.id,status:b.status,at:(0,k.whenOf)((0,k.toDate)(b.updatedAt)),...b.outcome?{outcome:(0,m.clip)(b.outcome,200)}:{}}}:{}}}let r=a=>{if((0,l.isPublicError)(a))return a.message;throw a};async function p(a){let b=(await (0,i.listRoutines)()).map(a=>`"${a.label}"`);return b.length?a?`There is no single routine called "${a}". The routines are: ${b.join(", ")}. Call again with one of those, or its ID.`:`Name the routine. The routines are: ${b.join(", ")}.`:"There are no routines yet."}a.s(["createRoutineTools",0,function(){return{[g.TOOL_NAMES.routine]:(0,d.tool)({description:q.description,inputSchema:q.parameters,execute:async a=>{if("list"===a.action)return{routines:(await (0,i.listRoutines)()).map(o)};let b=function(a){if(a.time&&a.everyHours)return"Give `time` or `everyHours`, not both.";let b=a.time?{kind:"daily",time:a.time,days:a.days?.length?a.days:[1,2,3,4,5,6,7]}:a.everyHours?{kind:"every",hours:a.everyHours}:null;if(!b)return null;let c=j.RoutineScheduleSchema.safeParse(b);return c.success?c.data:c.error.issues[0].message}(a);if("string"==typeof b)return b;if("create"===a.action){if(!b)return"Say when it starts: `time` (with `days`), or `everyHours`.";let c=j.RoutineInputSchema.safeParse({bot:a.bot??"",label:a.label??"",request:a.request??"",schedule:b});if(!c.success)return`${c.error.issues[0].message}. Nothing was made — call again with bot, label, request and when.`;let d=(await (0,h.listJobBots)()).map(a=>a.name);if(!d.some(a=>a.toLowerCase()===c.data.bot.toLowerCase()))return`There is no bot called "${c.data.bot}". The bots are: ${d.join(", ")}. Nothing was made — call again with one of those.`;let e=await (0,i.createRoutine)(c.data).catch(r);if("string"==typeof e)return e;let f=await (0,h.readKeepWorkingOn)()?"":" As things are set, it starts only while the app is open in a tab: a time that passes with it closed starts once when it is opened again. Settings › Routines has the switch that lets work go on with the app closed.";return{...o(e),note:`${e.bot} starts "${e.label}" by itself, ${(0,j.scheduleText)(e.schedule)}, first ${(0,k.whenOf)((0,k.toDate)(e.nextRunAt))}. Each start is a thread of its own, and its result reaches the conversation like any thread's.${f}`}}let c=a.routine?await (0,i.resolveRoutine)(a.routine):null;if(!c)return await p(a.routine);if("delete"===a.action)return await (0,i.deleteRoutine)(c.id),`"${c.label}" is deleted and starts no more. The threads it already opened stay.`;let d={...a.bot?{bot:a.bot}:{},...a.label?.trim()?{label:a.label.trim()}:{},...a.request?.trim()?{request:a.request.trim()}:{},...b?{schedule:b}:{},..."boolean"==typeof a.enabled?{enabled:a.enabled}:{}};if(!Object.keys(d).length)return"Nothing to change was given: bot, label, request, when, or enabled.";let e=await (0,i.updateRoutine)(c.id,d).catch(r);return"string"==typeof e?e:e?o(e):await p(a.routine)}})}}]),c()}catch(a){c(a)}},!1),622547,a=>a.a(async(b,c)=>{try{var d=a.i(47919),e=a.i(527990),f=a.i(723885),g=a.i(569572),h=a.i(762008),i=a.i(688034),j=a.i(725466),k=a.i(182248),l=b([j]);[j]=l.then?(await l)():l;let p=`Answer the question from the web. Lead with the answer, then
|
|
80
|
+
The line stays open until this runs, and drops once the goodbye being said is over.`,parameters:c.object({})},g=(0,b.tool)({description:f.description,inputSchema:f.parameters}),h={description:"Show a short word on your face for a few seconds.",parameters:c.object({text:c.string().describe(`Up to 8 characters: A-Z, 0-9, space and ${e.join(" ")}.`)})},i=(0,b.tool)({description:h.description,inputSchema:h.parameters});a.s(["callTools",0,function(){return{[d.TOOL_NAMES.end_call]:g,[d.TOOL_NAMES.emote]:i}}],375827)},467650,a=>{"use strict";var b=a.i(912714),c=a.i(527990),d=a.i(723885),e=a.i(569572),f=a.i(762008),g=a.i(684321),h=a.i(821415);a.s(["createLookTool",0,function(){return{[f.TOOL_NAMES.look_at]:(0,c.tool)({description:"See an image file yourself: a screenshot you took, a picture the user handed over, a chart you made. For what a picture shows — text files are read in the shell.",inputSchema:d.default.object({path:d.default.string().describe("Workspace-relative path to a png, jpg, webp or gif.")}),execute:async({path:a})=>{let c=await (0,h.insideWorkspace)(a.trim()),d=c?await (0,b.stat)(c).catch(()=>null):null;return c&&d?.isFile()?"image"!==(0,g.viewKindOf)(a)?`${a} is not an image. Read it in the shell instead.`:d.size>e.LOOK.maxBytes?`${a} is ${Math.ceil(d.size/1024/1024)} MB, over the ${e.LOOK.maxBytes/1024/1024} MB one look takes. Make a smaller copy in the shell first (on a Mac: sips -Z 1600 in.png --out out.png), then look at that.`:{path:a.trim(),mediaType:(0,g.mimeOf)(a),bytes:d.size}:`There is no file at ${a}. Give the path from the workspace root, as \`ls\` shows it.`},toModelOutput:async({output:a})=>{if("string"==typeof a)return{type:"text",value:a};let c=await (0,h.insideWorkspace)(a.path),d=c?await (0,b.readFile)(c).catch(()=>null):null;return d?{type:"content",value:[{type:"text",text:`${a.path}, as an image:`},{type:"file",mediaType:a.mediaType,data:{type:"data",data:d.toString("base64")}}]}:{type:"text",value:`${a.path} is no longer there.`}}})}}])},138902,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(762008),g=a.i(947950),h=a.i(821415),i=a.i(644468),j=b([g,i]);[g,i]=j.then?(await j)():j;let m={[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]:{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.")})}},n=(a,b)=>`${a.replace(/[^a-zA-Z0-9]+/g,"_")}__${b.replace(/[^a-zA-Z0-9_-]+/g,"_")}`.slice(0,64);async function k(a,b){let[c,e]=await Promise.all([(0,i.listConnectedToolNames)(),(0,g.findPinnedTools)(a)]),f={},j=(0,h.botArtifacts)(a);for(let a of e){let c=n(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,i.callConnectedTool)(b,a.server,a.name,c??void 0,{artifacts:j,abortSignal:d})}))}return c.length>e.length&&Object.assign(f,o(b,j)),f}async function l(a){let b=(await (0,i.listConnectedToolNames)(a)).map(a=>a.name);if(b.length)return`Tools on "${a}": ${b.join(", ")}.`;let c=await (0,i.listConnectedServerNames)();return c.length?`There is no server called "${a}". Connected: ${c.join(", ")}.`:"Nothing is connected."}let o=(a,b)=>({[f.TOOL_NAMES.tool_search]:(0,d.tool)({description:m[f.TOOL_NAMES.tool_search].description,inputSchema:m[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,i.findConnectedSchemas)(a.trim(),d);if(!e.length)return{tools:[],note:await l(a)};let f=d.filter(a=>!e.some(b=>b.name===a)),g=c.slice(8),h=[f.length?`Not on "${a}": ${f.join(", ")}.`:"",g.length?`Only 8 at a time — ask again for: ${g.join(", ")}.`:""].filter(Boolean);return{tools:e,...h.length?{note:h.join(" ")}:{}}}}),[f.TOOL_NAMES.tool_call]:(0,d.tool)({description:m[f.TOOL_NAMES.tool_call].description,inputSchema:m[f.TOOL_NAMES.tool_call].parameters,execute:async({server:c,tool:d,args:e},{abortSignal:f})=>(await (0,i.listConnectedToolNames)(c.trim())).some(a=>a.name===d.trim())?(0,i.callConnectedTool)(a,c.trim(),d.trim(),e??void 0,{artifacts:b,abortSignal:f}):{status:"error",text:await l(c)}})});a.s(["createMcpTools",0,k]),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=j.MEMORY_PATHS.map(a=>a.path.endsWith("/")?`${a.path}<name>`:a.path).join(", "),n=a=>({...a,facts:a.facts.map(({saidAt:a,...b})=>a?{...b,said:(0,g.saidStamp)(a)}:b),factCount:a.facts.length}),o=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.",p=a=>a>f.MEMORY_LIMITS.factsPerNote?` This note now holds ${a} facts, past the ${f.MEMORY_LIMITS.factsPerNote} one note holds well. Ask the user which of it is no longer true and delete what they name.`:"";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=p(d.facts.length);return e?{...n(d),note:e.trim()}:n(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("The group this note is found by — the person, project or topic its facts are about. Exactly as the listing writes it, or a new path following the same convention. A fact goes under the one note it is about; other notes name it rather than repeat it."),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 \`${h.TOOL_NAMES.memory_recall}\`. Null if this is new. A fact that stopped being true is replaced rather than deleted, and so is a note saying the same thing twice: replacing keeps what changed on the record, deleting does not.`),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 holds, so the listing alone tells which facts are inside. Give it for a new note, and again with new facts: rewritten from the current line and the new facts together, so it covers the whole note rather than only what was added. Null leaves it; ${j.MEMORY_ALWAYS_LISTED.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/partner might be "my partner" and their first name. 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.isAlwaysListed)(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&&!(0,j.isMemoryPath)(d))return{note:`Nothing was saved: "${d}" is not a path this listing can carry. Write it again under one of ${m}.`};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 o=await (0,i.writeNotes)([{path:h,description:k,aliases:g,facts:l}],a,b),q=o.unnamed.length?` ${o.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).`:"",r=o.notLoaded.length?` All ${f.MEMORY_LIMITS.carried} carried lines are taken, so ${o.notLoaded.map(a=>`"${a}"`).join(", ")} saved as an ordinary fact. Say which carried line you would drop for it and let them choose.`:"",s=n(o.notes[0]),t=e&&l.length&&!k?` Its line still reads "${s.description}"; if that no longer says what the note holds, send \`description\`.`:"";return{...s,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.${q}${r}${t}${p(s.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:o(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:o(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(n),note:e}}})})]),c()}catch(a){c(a)}},!1),617594,a=>a.a(async(b,c)=>{try{var d=a.i(527990),e=a.i(794219),f=a.i(569572),g=a.i(762008),h=a.i(221214),i=a.i(780946),j=a.i(643020),k=a.i(706210),l=a.i(293480),m=a.i(182248),n=b([h,i]);[h,i]=n.then?(await n)():n;let q={description:`Routines: work that starts by itself, each one a bot, the work and a time — once at a moment, a time of day on chosen days, or every few hours. List them, make one, change one, or delete one. Every start opens a thread like one started by hand; its result reaches the conversation the same way. At most ${f.ROUTINE.max} exist.`,parameters:e.object({action:e.enum(["list","create","change","delete"]),routine:e.string().nullish().describe("With change or delete: the routine, by its name or ID."),bot:e.string().nullish().describe("With create: a name from the bot list. With change: a new bot."),label:e.string().nullish().describe("With create: two or three words naming it, in the user's language. It names every thread the routine opens, on screen and out loud."),request:e.string().nullish().describe("With create: the whole of the work, handed to the bot as written every time it starts. Nobody is there then to fill in what is missing, so everything it needs goes here, in the user's own language and words. Their request, never your reading of it."),at:e.string().nullish().describe('Starts once, at this moment, "YYYY-MM-DD HH:MM" in the user\'s own time, then switches itself off. Count "in an hour" or "tomorrow at eight" from **Now**. Give one of `at`, `time` or `everyHours`.'),time:e.string().nullish().describe('Starts at this time of day, 24-hour "HH:MM" in the user\'s own time, on `days`. Give one of `at`, `time` or `everyHours`.'),days:e.array(e.number().int().min(1).max(7)).nullish().describe("With `time`: the days it starts, 1 Monday to 7 Sunday. Omit for every day."),everyHours:e.number().int().nullish().describe(`Starts again this many hours after it last started, ${f.ROUTINE.minHours} at least. Give one of \`at\`, \`time\` or \`everyHours\`.`),enabled:e.boolean().nullish().describe("With change: false switches it off without deleting it, true back on.")})};function o(a){let b=a.runs[0];return{id:a.id,label:a.label,bot:a.bot,when:(0,j.scheduleText)(a.schedule),enabled:a.enabled,...a.enabled?{next:(0,k.whenOf)((0,k.toDate)(a.nextRunAt))}:{},request:(0,m.clip)(a.request,300),...b?{lastRun:{thread:b.id,status:b.status,at:(0,k.whenOf)((0,k.toDate)(b.updatedAt)),...b.outcome?{outcome:(0,m.clip)(b.outcome,200)}:{}}}:{}}}let r=a=>{if((0,l.isPublicError)(a))return a.message;throw a};async function p(a){let b=(await (0,i.listRoutines)()).map(a=>`"${a.label}"`);return b.length?a?`There is no single routine called "${a}". The routines are: ${b.join(", ")}. Call again with one of those, or its ID.`:`Name the routine. The routines are: ${b.join(", ")}.`:"There are no routines yet."}a.s(["createRoutineTools",0,function(){return{[g.TOOL_NAMES.routine]:(0,d.tool)({description:q.description,inputSchema:q.parameters,execute:async a=>{if("list"===a.action)return{routines:(await (0,i.listRoutines)()).map(o)};let b=function(a){if([a.at,a.time,a.everyHours].filter(Boolean).length>1)return"Give one of `at`, `time` or `everyHours`, not two.";let b=a.at?{kind:"once",at:a.at}:a.time?{kind:"daily",time:a.time,days:a.days?.length?a.days:[1,2,3,4,5,6,7]}:a.everyHours?{kind:"every",hours:a.everyHours}:null;if(!b)return null;let c=j.RoutineScheduleSchema.safeParse(b);return c.success?c.data:c.error.issues[0].message}(a);if("string"==typeof b)return b;if("create"===a.action){if(!b)return"Say when it starts: `at`, `time` (with `days`), or `everyHours`.";let c=j.RoutineInputSchema.safeParse({bot:a.bot??"",label:a.label??"",request:a.request??"",schedule:b});if(!c.success)return`${c.error.issues[0].message}. Nothing was made — call again with bot, label, request and when.`;let d=(await (0,h.listJobBots)()).map(a=>a.name);if(!d.some(a=>a.toLowerCase()===c.data.bot.toLowerCase()))return`There is no bot called "${c.data.bot}". The bots are: ${d.join(", ")}. Nothing was made — call again with one of those.`;let e=await (0,i.createRoutine)(c.data).catch(r);if("string"==typeof e)return e;let f=await (0,h.readKeepWorkingOn)()?"":" As things are set, it starts only while the app is open in a tab: a time that passes with it closed starts once when it is opened again. Settings › Routines has the switch that lets work go on with the app closed.",g=(0,k.whenOf)((0,k.toDate)(e.nextRunAt));return{...o(e),note:"once"===e.schedule.kind?`${e.bot} starts "${e.label}" once, ${g}, and the routine then switches itself off. The start is a thread of its own, and its result reaches the conversation like any thread's.${f}`:`${e.bot} starts "${e.label}" by itself, ${(0,j.scheduleText)(e.schedule)}, first ${g}. Each start is a thread of its own, and its result reaches the conversation like any thread's.${f}`}}let c=a.routine?await (0,i.resolveRoutine)(a.routine):null;if(!c)return await p(a.routine);if("delete"===a.action)return await (0,i.deleteRoutine)(c.id),`"${c.label}" is deleted and starts no more. The threads it already opened stay.`;let d={...a.bot?{bot:a.bot}:{},...a.label?.trim()?{label:a.label.trim()}:{},...a.request?.trim()?{request:a.request.trim()}:{},...b?{schedule:b}:{},..."boolean"==typeof a.enabled?{enabled:a.enabled}:{}};if(!Object.keys(d).length)return"Nothing to change was given: bot, label, request, when, or enabled.";let e=await (0,i.updateRoutine)(c.id,d).catch(r);return"string"==typeof e?e:e?o(e):await p(a.routine)}})}}]),c()}catch(a){c(a)}},!1),622547,a=>a.a(async(b,c)=>{try{var d=a.i(47919),e=a.i(527990),f=a.i(723885),g=a.i(569572),h=a.i(762008),i=a.i(688034),j=a.i(725466),k=a.i(182248),l=b([j]);[j]=l.then?(await l)():l;let p=`Answer the question from the web. Lead with the answer, then
|
|
79
81
|
what supports it. Say plainly what you could not find or confirm — do not fill
|
|
80
82
|
the gap with a guess. Every number carries the date you saw it. Be brief: this
|
|
81
83
|
is read by another model, not by a person.`,q=f.default.string().describe("What you want to know, as one full question. Put the place and the time in when they matter — the searcher sees nothing but this line.");async function m(a,b,c){let d=await fetch("https://api.exa.ai/search",{method:"POST",signal:c,headers:{"content-type":"application/json","x-api-key":a},body:JSON.stringify({query:b,type:"auto",numResults:g.SEARCH.sources,contents:{text:{maxCharacters:g.SEARCH.excerptChars},livecrawl:"fallback",livecrawlTimeout:5e3}})});if(!d.ok)return{text:`Exa answered ${d.status}: ${(0,k.clip)((await d.text()).trim(),200)}`,sources:[]};let e=(await d.json()).results??[];if(!e.length)return{text:"Nothing came back for that. Try other words, or open the page itself.",sources:[]};let f=e.flatMap(a=>a.url?.trim()?[{url:a.url.trim(),...a.title?.trim()?{title:a.title.trim()}:{}}]:[]);return{text:e.map(a=>{let b=[a.title?.trim(),a.url?.trim()].filter(Boolean).join(" — "),c=a.publishedDate?.slice(0,10);return[c?`${b} \xb7 ${c}`:b,a.text?.trim()].filter(Boolean).join("\n")}).join("\n\n"),sources:f}}async function n(a,b,c){let{text:e,sources:f}=await (0,d.generateText)({model:a.model,tools:a.tools,instructions:p,prompt:b,abortSignal:c}),h=[...new Set(f.flatMap(a=>"url"===a.sourceType?[a.title?`${a.title} — ${a.url}`:a.url]:[]))].slice(0,g.SEARCH.sources);return{text:[e.trim(),h.length?`Sources:
|
|
@@ -112,13 +114,13 @@ Cover all of it, and prefer a fact over a description of a fact:
|
|
|
112
114
|
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.
|
|
113
115
|
|
|
114
116
|
${j}`,usage:x(i)}}let x=a=>({input:a.inputTokens??0,output:a.outputTokens??0});a.s(["resumeTranscript",0,function(a,b=new Map){let c=new Map,d=new Set;for(let b of a)if(("tool"===b.role||"assistant"===b.role)&&Array.isArray(b.content))for(let a of b.content)"tool-result"===a.type&&(c.has(a.toolCallId)||c.set(a.toolCallId,a),"assistant"===b.role&&d.add(a.toolCallId));let e=[],f=new Set;for(let g of a){if("tool"===g.role){let a=g.content.filter(a=>"tool-result"!==a.type);a.length&&e.push({...g,content:a});continue}if("assistant"!==g.role||"string"==typeof g.content){e.push(g);continue}let a=[],h=[];for(let e of g.content){if("tool-call"!==e.type){h.push(e);continue}if(f.has(e.toolCallId))continue;let g=e.input;if("string"==typeof g)try{g=JSON.parse(g)}catch{g=void 0}if(!e.toolCallId||void 0===g){h.push({type:"text",text:"A tool argument stream was interrupted before a complete call was recorded. Inspect the saved work before continuing."});continue}let i=e.toolName===k.TOOL_NAMES.send_message?b.get(e.toolCallId):void 0,j=c.get(e.toolCallId)??(i?{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"json",value:i}}:void 0);if(e.providerExecuted&&(!j||!d.has(e.toolCallId))){h.push({type:"text",text:j?`The provider operation ${e.toolName} returned this data before its native continuation was interrupted: ${JSON.stringify(j.output)}`:`The provider operation ${e.toolName} was interrupted without a recorded result. Its remote execution state is unknown.`});continue}f.add(e.toolCallId),h.push({...e,input:g}),d.has(e.toolCallId)||a.push(j??{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:"No result: execution was interrupted before a result was recorded. The outcome is unknown. Inspect the current state before repeating the action."}})}h.length&&e.push({...g,content:h}),a.length&&e.push({role:"tool",content:a})}return e},"runBot",0,s]),c()}catch(a){c(a)}},!1),674986,a=>a.a(async(b,c)=>{try{var d=a.i(136340),e=a.i(203469),f=a.i(569572),g=a.i(875931),h=a.i(735502),i=a.i(569549),j=a.i(684321),k=a.i(821415),l=a.i(956802),m=a.i(176668),n=a.i(293480),o=a.i(8412),p=a.i(182248),q=a.i(221214),r=a.i(654034),s=a.i(446957),t=a.i(839430),u=a.i(109955),v=a.i(344853),w=b([g,h,i,q,r,t,v]);[g,h,i,q,r,t,v]=w.then?(await w)():w;let L=globalThis.__roomRuns??=new Map,M=globalThis.__roomThreadLock??=(0,o.createKeyedLock)(),N=globalThis.__roomPausing??={current:Promise.resolve()},O=globalThis.__roomCompactAsked??=new Set,P=(a,b)=>`${a}
|
|
115
|
-
${b}`;async function x(a){let b=await (0,q.findJobBot)(a.bot);(!b||b.disabled)&&(0,n.publicError)("Choose an enabled bot.");let{from:c,routine:d,...e}={...a,bot:b.name},f=(0,h.buildThreadOpening)({bot:e.bot,request:e.request,from:c,routine:d}),g=await (0,v.insertThread)({...e,routineId:d?.id??null,opening:f});return await z(g.id),g.id}async function y(a,b,c="user",d,e){let f=null;return await M(a,async()=>{let g=await (0,v.findThread)(a);if(g||(0,n.publicError)("No such thread."),d){let b=(await (0,t.listRoomWork)(a)).find(a=>a.bot.toLowerCase()===d.trim().toLowerCase());b&&b.bot!==u.ROOM_THURSDAY||(0,n.publicError)("Choose a participant in this thread."),d=b.bot}b.trim()===s.THREAD_CONTINUE&&(0,s.isAppStop)(g.pending)?(await (0,t.resumeRoom)(a),(await (0,t.listRoomWork)(a)).some(a=>"queued"===a.state)||(f=await (0,t.tellRoom)(a,"Continue from the saved conversation.","user"===c?"The user":u.ROOM_THURSDAY,d,void 0,!1))):f=await (0,t.tellRoom)(a,b,"user"===c?"The user":u.ROOM_THURSDAY,d,e)}),await z(a),f}async function z(a){await M(a,async()=>{if(!e.presence.watching&&!await (0,q.readKeepWorkingOn)()){let b=await (0,v.findThread)(a);b?.status!=="running"||[...L.values()].some(b=>b.threadId===a)||await (0,t.pauseRoom)(a,"The app is not open. Work resumes when it returns.",!0);return}for(let b=0;b<2;b++){let b;for(;b=await (0,t.claimRoomWork)(a);)!function(a){let b,c=new AbortController,d=new Promise(a=>{b=a});L.set(a.id,{threadId:a.threadId,stop:c,done:d}),A(a,c.signal).catch(b=>m.logger.error(`thread ${a.threadId}: participant`,b)).finally(()=>{L.delete(a.id),b(),z(a.threadId).catch(b=>m.logger.error(`thread ${a.threadId}: scheduling`,b))})}(b);await (0,t.settleRoom)(a)}})}async function A(a,b){let c=await B(a,b);if(c?.failure?.retry&&!b.aborted&&(await (0,t.noteRoomBreak)(a,c.failure.message),await (0,d.setTimeout)(f.BOT_RUN.retryMs,void 0,{signal:b}).catch(()=>{}),b.aborted||(c=await B(a,b))),!c||b.aborted)return;let g=c.failure?.message,h=c.ending;if(g||!h||h.stopped){let b=g??"The turn was interrupted. Continue from the saved conversation.";M(a.threadId,async()=>{let c=(await (0,t.listRoomWork)(a.threadId)).find(b=>b.id===a.id);if(c?.state!=="running"||c.generation!==a.generation)return;let d=C(a.threadId);await (0,t.pauseRoom)(a.threadId,b),await d}).catch(b=>m.logger.error(`thread ${a.threadId}: pausing`,b));return}await (0,t.finishRoomWork)(a,h.text);let n=await (0,v.findThread)(a.threadId);if(n?.status==="done"){await (0,i.isAnyCallLive)()||(0,l.desktopNotify)(n.label,n.outcome??"");let a=await (0,k.filesOnDisk)((0,j.pathsIn)(n.outcome??""),null),b=a.findIndex(j.opensOnFinish);e.appEvents.emit({type:"finished",threadId:n.id,label:n.label,bot:n.bot,words:(0,p.plainText)(n.outcome??"").slice(0,f.FINISHED_NOTICE.words),paths:b>0?[a[b],...a.filter((a,c)=>c!==b)]:a})}}async function B(a,b){let c=new Q(a,b),d=null,e=null;try{let f=await (0,v.findThread)(a.threadId);if(!f)return null;(await (0,t.listParticipantTranscript)(a.threadId,a.bot)).length||await (0,t.appendRoomMessage)(a.threadId,{bot:a.bot,parent:a.id,role:"user",content:`Request: ${f.request}
|
|
116
|
-
Coordinator: ${f.bot}. Continue as ${a.bot} in this thread.`,hidden:!0}),await (0,t.consumeRoomInbox)(a);let g=await (0,t.listParticipantTranscript)(a.threadId,a.bot);await (0,r.runBot)({bot:a.bot,messages:(0,r.resumeTranscript)(g,await (0,t.listRoomReceipts)(a.threadId,a.bot,g))},{signal:b,threadId:a.threadId,parent:a.id,caller:a.caller,owner:f.bot,contextBudget:await (0,t.roomContextBudget)(a.threadId,a.bot),compactNow:()=>O.delete(P(a.threadId,a.bot)),session:(0,k.botBrowserSession)(a.threadId,a.bot),notes:()=>(0,t.consumeRoomInbox)(a),send:async c=>{b.throwIfAborted();let d=c.to.trim();if(d.toLowerCase()===u.ROOM_THURSDAY.toLowerCase())d=u.ROOM_THURSDAY;else{let a=await (0,q.findJobBot)(d);(!a||a.disabled)&&(0,n.publicError)(`No enabled bot named "${d}".`),d=a.name}let e=await (0,t.sendRoomMessage)(a,{...c,to:d});return z(a.threadId).catch(a=>m.logger.error("room message scheduling",a)),e},emit:async g=>{(!b.aborted||"tool-result"===g.type)&&(await c.on(g),"step"===g.type&&await (0,v.addThreadUsage)(a.threadId,g.usage,a.bot===f.bot?{tokens:g.usage.input,budget:g.budget}:null),"compact"===g.type&&await (0,v.addThreadUsage)(a.threadId,g.usage),"turn-end"===g.type&&(d=g),"error"===g.type&&(e={message:g.message,retry:g.retry},g.budget&&await (0,t.lowerRoomContextBudget)(a,g.budget)))}})}catch(c){b.aborted||(m.logger.error(`thread ${a.threadId}: ${a.bot} broke`,c),e={message:(0,g.modelErrorToString)(c),retry:!(0,n.isPublicError)(c)&&!(0,g.isProviderRefusal)(c)})}return{ending:d,failure:e}}class Q{work;signal;lane;assistant;tool;parts;calls;results;constructor(a,b){this.work=a,this.signal=b,this.lane=(0,p.PromiseChain)(),this.assistant=null,this.tool=null,this.parts={assistant:[],tool:[]},this.calls=new Set,this.results=new Set}async write(a,b,c=!1){let d={bot:this.work.bot,parent:this.work.id,role:b.role,content:b.content,compact:c,note:c};return null===a?(0,t.appendRoomMessage)(this.work.threadId,d):(await (0,v.upsertMessage)(this.work.threadId,a,d),a)}on(a){return this.lane(async()=>{if(!this.signal.aborted||"tool-result"===a.type)if("text"===a.type)this.parts.assistant.push({type:"text",text:a.text}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant});else if("tool"===a.type){if(this.calls.has(a.id)){let b=this.parts.assistant.find(b=>"tool-call"===b.type&&b.toolCallId===a.id);b&&"tool-call"===b.type&&a.providerOptions&&(b.providerOptions=a.providerOptions,this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant}));return}this.calls.add(a.id),this.parts.assistant.push({type:"tool-call",toolCallId:a.id,toolName:a.name,input:a.input,...a.providerExecuted?{providerExecuted:!0}:{},...a.providerOptions?{providerOptions:a.providerOptions}:{}}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant})}else if("tool-result"===a.type){if(this.results.has(a.id))return;this.results.add(a.id),this.parts.tool.push({type:"tool-result",toolCallId:a.id,toolName:a.name,output:a.error?{type:"error-text",value:String(a.output)}:"string"==typeof a.output?{type:"text",value:a.output}:{type:"json",value:a.output}}),this.tool=await this.write(this.tool,{role:"tool",content:this.parts.tool})}else if("step"===a.type){let b=[this.assistant,this.tool];for(let[c,d]of a.messages.entries())await this.write(b[c]??null,d);let c=b.slice(a.messages.length).filter(a=>null!==a);c.length&&await (0,v.deleteMessages)(this.work.threadId,c),this.assistant=this.tool=null,this.parts={assistant:[],tool:[]}}else"compact"===a.type&&await this.write(null,{role:"user",content:a.text},!0)})}}async function C(a){let b=[...L.values()].filter(b=>b.threadId===a);for(let a of b)a.stop.abort();await Promise.all(b.map(a=>a.done))}async function D(a){await M(a,async()=>{let b=await (0,v.findThread)(a);b||(0,n.publicError)("No such thread."),b.endedAt&&(0,n.publicError)("That thread has already ended."),await (0,t.cancelRoom)(a),await (0,v.updateThread)(a,{status:"cancelled",outcome:null,pending:null,seen:!0,endedAt:new Date}),await C(a),await (0,k.closeJobShell)(a)})}async function E(a){return M(a,()=>F(a))}async function F(a){let b=await (0,v.findThread)(a);await (0,t.cancelRoom)(a),await C(a),await (0,k.removeJobBrowsers)(a);let c=await (0,v.deleteThread)(a);return c&&b&&await (0,k.removeJobScratch)(a,b.label),c}async function G(){let a=0;for(let b of(await (0,v.listThreadFolders)()))("done"===b.status||"cancelled"===b.status)&&await M(b.id,async()=>{let c=await (0,v.findThread)(b.id);(c?.status==="done"||c?.status==="cancelled")&&await F(b.id)&&(a+=1)});return a}async function H(){let a=Date.now()-f.WORKSPACE_KEEP.forMs,b=b=>("done"===b.status||"cancelled"===b.status)&&(b.endedAt??b.updatedAt).getTime()<a,c=new Set(await (0,k.listScratchFolders)()),d=[];for(let a of(await (0,v.listThreadFolders)())){let e=(0,k.jobScratch)(a.id,a.label);c.delete(e)&&b(a)&&await M(a.id,async()=>{let c=await (0,v.findThread)(a.id);c&&b(c)&&(await (0,k.closeHiddenBrowser)(a.id),await (0,k.removeJobScratch)(a.id,a.label),d.push(e))})}return d.push(...await (0,k.removeUnchangedFolders)([...c])),await (0,k.pruneJobFiles)(),d.length&&m.logger.info(`cleared ${d.length} old job folder(s): ${d.join(", ")}`),d}async function I(){for(let a of(await (0,v.listRunningThreadIds)()))await M(a,async()=>{[...L.values()].some(b=>b.threadId===a)||(await (0,v.findThread)(a))?.status==="running"&&await (0,t.pauseRoom)(a,"The server restarted. Resume from the saved conversation.")})}async function J(a,b=!1){let c=(async()=>{let c=await (0,v.listRunningThreadIds)();await Promise.all(c.map(c=>M(c,async()=>{(await (0,v.findThread)(c))?.status==="running"&&(await C(c),await (0,t.pauseRoom)(c,a,b))})))})();N.current=c,await c}async function K(){if(await N.current,e.presence.watching)for(let a of(await (0,v.listAutoStoppedThreads)()))await M(a,async()=>{let b=await (0,v.findThread)(a);b?.status==="waiting"&&b.pending?.auto&&await (0,t.resumeRoom)(a,!1)}),await z(a)}a.s(["answerThread",0,y,"askCompact",0,function(a,b){O.add(P(a,b))},"cancelThread",0,D,"pauseThreads",0,J,"removeFinishedThreads",0,G,"removeThread",0,E,"resumeStoppedThreads",0,K,"startThread",0,x,"sweepJobFiles",0,H,"sweepThreads",0,I]),c()}catch(a){c(a)}},!1),317844,a=>a.a(async(b,c)=>{try{var d,e=a.i(106450),f=a.i(64203),g=a.i(569572),h=a.i(176668),i=a.i(182248),j=a.i(947950),k=a.i(899284),l=b([j]);[j]=l.then?(await l)():l;class m extends Error{serverName;authorizationUrl;constructor(a,b){super(`MCP server "${a}" requires authorization`),this.serverName=a,this.authorizationUrl=b,this.name="McpAuthRequiredError"}}class n{store;serverName;oauth;callbackUrl;clientName;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"}],g=f.filter(a=>!a.path.endsWith("/")).map(a=>a.path),h=f.filter(a=>a.path.endsWith("/")).map(a=>a.path.slice(0,-1)),i=RegExp(`^(?:${g.join("|")}|(?:${h.join("|")})/.+)$`),j=["profile","preferences"];a.s(["MEMORY_ALWAYS_LISTED",0,j,"MEMORY_PATHS",0,f,"appNoteLine",0,a=>f.find(b=>b.path===a)?.of??null,"isAlwaysListed",0,a=>j.includes(a),"isMemoryPath",0,a=>i.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)}])},780946,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(258261),f=a.i(530385),g=a.i(203469),h=a.i(569572),i=a.i(184838),j=a.i(714428),k=a.i(221214),l=a.i(293480),m=a.i(643020),n=b([i,k]);[i,k]=n.then?(await n)():n;let y=()=>g.appEvents.emit({type:"routines"});async function o(a,b){return i.database.select({id:j.threadTable.id,status:j.threadTable.status,outcome:j.threadTable.outcome,updatedAt:j.threadTable.updatedAt}).from(j.threadTable).where((0,d.eq)(j.threadTable.routineId,a)).orderBy((0,f.desc)(j.threadTable.createdAt)).limit(b)}let z=async a=>{let{createdAt:b,...c}=a;return{...c,runs:await o(a.id,h.ROUTINE.runsShown)}};async function p(){let a=await i.database.select().from(j.routineTable).orderBy(j.routineTable.createdAt);return Promise.all(a.map(z))}async function q(a){let[b]=await i.database.select().from(j.routineTable).where((0,d.eq)(j.routineTable.id,a));return b?z(b):null}async function r(a){let b=await q(a.trim());if(b)return b;let c=a.trim().toLowerCase(),d=(await p()).filter(a=>a.label.toLowerCase()===c);return 1===d.length?d[0]:null}async function s(a){let b=await (0,k.findJobBot)(a);return(!b||b.disabled)&&(0,l.publicError)("Choose an enabled bot."),b.name}async function t(a){let[{total:b}]=await i.database.select({total:(0,e.count)()}).from(j.routineTable);b>=h.ROUTINE.max&&(0,l.publicError)(`There are already ${h.ROUTINE.max} routines. Delete one to make another.`);let[c]=await i.database.insert(j.routineTable).values({id:crypto.randomUUID(),...a,bot:await s(a.bot),nextRunAt:(0,m.nextRun)(a.schedule,new Date)}).returning();return y(),z(c)}async function u(a,b){let[c]=await i.database.select().from(j.routineTable).where((0,d.eq)(j.routineTable.id,a));if(!c)return null;let e=b.schedule??c.schedule,f=!!b.schedule||b.enabled&&!c.enabled,[g]=await i.database.update(j.routineTable).set({...b,...b.bot?{bot:await s(b.bot)}:{},...f?{nextRunAt:(0,m.nextRun)(e,new Date)}:{}}).where((0,d.eq)(j.routineTable.id,a)).returning();return y(),z(g)}async function v(a){let b=await i.database.delete(j.routineTable).where((0,d.eq)(j.routineTable.id,a)).returning({id:j.routineTable.id});return b.length&&y(),b.length>0}async function w(a){return(await o(a,1))[0]??null}async function x(a){return(await i.database.select({id:j.threadTable.id}).from(j.threadTable).where((0,d.and)((0,d.eq)(j.threadTable.routineId,a),(0,d.eq)(j.threadTable.seen,!1),(0,d.inArray)(j.threadTable.status,["done","cancelled"])))).map(a=>a.id)}a.s(["createRoutine",0,t,"deleteRoutine",0,v,"findRoutine",0,q,"latestRun",0,w,"listRoutines",0,p,"listUnseenRunIds",0,x,"resolveRoutine",0,r,"updateRoutine",0,u]),c()}catch(a){c(a)}},!1),643020,a=>{"use strict";var b=a.i(723885),c=a.i(569572),d=a.i(706210);let e=b.default.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"A time is HH:MM, 00:00 to 23:59"),f=b.default.discriminatedUnion("kind",[b.default.object({kind:b.default.literal("daily"),time:e,days:b.default.array(b.default.number().int().min(1).max(7)).min(1,"Pick at least one day").transform(a=>[...new Set(a)].sort((a,b)=>a-b))}),b.default.object({kind:b.default.literal("every"),hours:b.default.number().int().min(c.ROUTINE.minHours,`No more often than every ${c.ROUTINE.minHours}h`).max(168)})]),g=b.default.object({bot:b.default.string().trim().min(1,"Pick a bot"),label:b.default.string().trim().min(1,"Give it a name").max(80),request:b.default.string().trim().min(1,"Say what it should do"),schedule:f}),h=b.default.object({id:b.default.string(),status:b.default.enum(["running","waiting","done","cancelled"]),outcome:b.default.string().nullable(),updatedAt:d.DateLikeSchema});g.extend({id:b.default.string(),enabled:b.default.boolean(),nextRunAt:d.DateLikeSchema,runs:b.default.array(h)});let i=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];a.s(["RoutineInputSchema",0,g,"RoutineScheduleSchema",0,f,"nextRun",0,function(a,b){if("every"===a.kind)return new Date(b.getTime()+36e5*a.hours);let[c,d]=a.time.split(":").map(Number);for(let e=0;e<=7;e++){let f=new Date(b);f.setDate(f.getDate()+e),f.setHours(c,d,0,0);let g=0===f.getDay()?7:f.getDay();if(f>b&&a.days.includes(g))return f}return new Date(b.getTime()+864e5)},"scheduleText",0,function(a){if("every"===a.kind)return 1===a.hours?"Every hour":`Every ${a.hours} hours`;let{days:b,time:c}=a;if(7===b.length)return`Daily ${c}`;if(1===b.length)return`${i[b[0]-1]} ${c}`;let d=b.every((a,c)=>0===c||a===b[c-1]+1)?`${i[b[0]-1]}–${i[b.at(-1)-1]}`:b.map(a=>i[a-1]).join(" ");return`Daily ${c} \xb7 ${d}`}])},487591,422807,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(203469),e=a.i(569572);a.i(821415),a.i(176668);let f=a=>a.trim().toLowerCase().replace(/^[a-z]+:\/\//,"").replace(/^www\./,"").replace(/[/?#].*$/,"");a.s(["siteOf",0,f],422807);let g=(0,c.join)(e.DATA_DIR,e.PATHS.signIns),h=a=>(0,c.join)(g,`${encodeURIComponent(f(a))}.json`),i=()=>d.appEvents.emit({type:"signins"});async function j(a){try{return JSON.parse(await (0,b.readFile)(h(a),"utf8"))}catch{return null}}async function k(a){await (0,b.mkdir)(g,{recursive:!0}),await (0,b.writeFile)(h(a.site),JSON.stringify(a),{mode:384}),i()}async function l(){let a=await (0,b.readdir)(g).catch(()=>[]);return(await Promise.all(a.filter(a=>a.endsWith(".json")).map(a=>j(decodeURIComponent(a.slice(0,-5)))))).flatMap(a=>a?[(({state:a,...b})=>b)(a)]:[]).sort((a,b)=>a.site.localeCompare(b.site))}async function m(a){let b=f(a.site),c=await j(b),d={site:b,account:a.account.trim()||b,bots:[...new Set([...c?.bots??[],a.bot])],asking:(c?.asking??[]).filter(b=>b!==a.bot),keptAt:new Date().toISOString(),usedAt:c?.usedAt??null,state:a.state};return await k(d),(({state:a,...b})=>b)(d)}async function n(a,b){let c=await j(a);if(!c)return{kind:"none",kept:(await l()).map(a=>a.site)};if(!c.bots.includes(b))return c.asking.includes(b)||await k({...c,asking:[...c.asking,b]}),{kind:"ask",signIn:(({state:a,...b})=>b)(c)};let d={...c,usedAt:new Date().toISOString()};return await k(d),{kind:"state",signIn:(({state:a,...b})=>b)(d),state:c.state}}async function o(a,b,c){let d=await j(a);d&&await k({...d,bots:c?[...new Set([...d.bots,b])]:d.bots.filter(a=>a!==b),asking:d.asking.filter(a=>a!==b)})}async function p(a){await (0,b.rm)(h(a),{force:!0}),i()}a.s(["borrowSignIn",0,n,"keepSignIn",0,m,"removeSignIn",0,p,"setSignInBot",0,o],487591)},138100,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(569572),e=a.i(821415),f=a.i(176668),g=a.i(182248),h=a.i(762805);let i=(0,c.join)(d.APP_DIR,d.PATHS.skills.default),j=(0,c.join)(d.DATA_DIR,d.PATHS.skills.custom),k=a=>(0,c.join)(e.WORKSPACE,(0,e.botFolder)(a),d.PATHS.skills.own);async function l(a,e){let f=(0,c.join)(d.APP_DIR,d.PATHS.skills.seeds,a.toLowerCase());await (0,b.cp)(f,k(e),{recursive:!0,force:!1}).catch(a=>{if("ENOENT"!==a.code)throw a})}async function m(a,b){let c=[],d=new Set;for(let e of b){let b;try{b=await a.readdir(e,{withFileTypes:!0})}catch{continue}for(let i of b){let b,j;if(!i.isDirectory())continue;let k=`${e}/${i.name}`,l=`${k}/SKILL.md`;try{b=await a.readFile(l,"utf-8")}catch{continue}try{j=(0,h.parseFrontmatter)(b)}catch(a){f.logger.warn(`skill ${k}: SKILL.md front matter did not load — ${(0,g.errorToString)(a)}`);continue}!d.has(j.name)&&(d.add(j.name),j.disabled||c.push({name:j.name,description:j.description,path:k}))}}return c}a.s(["giveSeedSkills",0,l,"loadSkills",0,(a,b)=>m(a,b?[i,k(b),j]:[i,j])])},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`---
|
|
117
|
+
${b}`;async function x(a){let b=await (0,q.findJobBot)(a.bot);(!b||b.disabled)&&(0,n.publicError)("Choose an enabled bot.");let{from:c,routine:d,...e}={...a,bot:b.name},f=(0,h.buildThreadOpening)({bot:e.bot,request:e.request,from:c,routine:d}),g=await (0,v.insertThread)({...e,routineId:d?.id??null,opening:f});return await z(g.id),g.id}async function y(a,b,c="user",d,e){let f=null;return await M(a,async()=>{let g=await (0,v.findThread)(a);if(g||(0,n.publicError)("No such thread."),d){let b=(await (0,t.listRoomWork)(a)).find(a=>a.bot.toLowerCase()===d.trim().toLowerCase());b&&b.bot!==u.ROOM_THURSDAY||(0,n.publicError)("Choose a participant in this thread."),d=b.bot}b.trim()===s.THREAD_CONTINUE&&(0,s.isAppStop)(g.pending)?(await (0,t.resumeRoom)(a),(await (0,t.listRoomWork)(a)).some(a=>"queued"===a.state)||(f=await (0,t.tellRoom)(a,"Continue from the saved conversation.","user"===c?"The user":u.ROOM_THURSDAY,d,void 0,!1))):f=await (0,t.tellRoom)(a,b,"user"===c?"The user":u.ROOM_THURSDAY,d,e)}),await z(a),f}async function z(a){await M(a,async()=>{if(!e.presence.watching&&!await (0,q.readKeepWorkingOn)()){let b=await (0,v.findThread)(a);b?.status!=="running"||[...L.values()].some(b=>b.threadId===a)||await (0,t.pauseRoom)(a,"The app is not open. Work resumes when it returns.",!0);return}for(let b=0;b<2;b++){let b;for(;b=await (0,t.claimRoomWork)(a);)!function(a){let b,c=new AbortController,d=new Promise(a=>{b=a});L.set(a.id,{threadId:a.threadId,stop:c,done:d}),A(a,c.signal).catch(b=>m.logger.error(`thread ${a.threadId}: participant`,b)).finally(()=>{L.delete(a.id),b(),z(a.threadId).catch(b=>m.logger.error(`thread ${a.threadId}: scheduling`,b))})}(b);await (0,t.settleRoom)(a)}})}async function A(a,b){let c=await B(a,b);if(c?.failure?.retry&&!b.aborted&&(await (0,t.noteRoomBreak)(a,c.failure.message),await (0,d.setTimeout)(f.BOT_RUN.retryMs,void 0,{signal:b}).catch(()=>{}),b.aborted||(c=await B(a,b))),!c||b.aborted)return;let g=c.failure?.message,h=c.ending;if(g||!h||h.stopped){let b=g??"The turn was interrupted. Continue from the saved conversation.";M(a.threadId,async()=>{let c=(await (0,t.listRoomWork)(a.threadId)).find(b=>b.id===a.id);if(c?.state!=="running"||c.generation!==a.generation)return;let d=C(a.threadId);await (0,t.pauseRoom)(a.threadId,b),await d}).catch(b=>m.logger.error(`thread ${a.threadId}: pausing`,b));return}await (0,t.finishRoomWork)(a,h.text);let n=await (0,v.findThread)(a.threadId);if(n?.status==="done"){e.presence.watching||await (0,i.isAnyCallLive)()||(0,l.desktopNotify)(n.label,n.outcome??"");let a=await (0,k.filesOnDisk)((0,j.pathsIn)(n.outcome??""),null),b=a.findIndex(j.opensOnFinish);e.appEvents.emit({type:"finished",threadId:n.id,label:n.label,bot:n.bot,words:(0,p.plainText)(n.outcome??"").slice(0,f.FINISHED_NOTICE.words),paths:b>0?[a[b],...a.filter((a,c)=>c!==b)]:a})}}async function B(a,b){let c=new Q(a,b),d=null,e=null;try{let f=await (0,v.findThread)(a.threadId);if(!f)return null;(await (0,t.listParticipantTranscript)(a.threadId,a.bot)).length||await (0,t.appendRoomMessage)(a.threadId,{bot:a.bot,parent:a.id,role:"user",content:`Request: ${f.request}
|
|
118
|
+
Coordinator: ${f.bot}. Continue as ${a.bot} in this thread.`,hidden:!0}),await (0,t.consumeRoomInbox)(a);let g=await (0,t.listParticipantTranscript)(a.threadId,a.bot);await (0,r.runBot)({bot:a.bot,messages:(0,r.resumeTranscript)(g,await (0,t.listRoomReceipts)(a.threadId,a.bot,g))},{signal:b,threadId:a.threadId,parent:a.id,caller:a.caller,owner:f.bot,contextBudget:await (0,t.roomContextBudget)(a.threadId,a.bot),compactNow:()=>O.delete(P(a.threadId,a.bot)),session:(0,k.botBrowserSession)(a.threadId,a.bot),notes:()=>(0,t.consumeRoomInbox)(a),send:async c=>{b.throwIfAborted();let d=c.to.trim();if(d.toLowerCase()===u.ROOM_THURSDAY.toLowerCase())d=u.ROOM_THURSDAY;else{let a=await (0,q.findJobBot)(d);(!a||a.disabled)&&(0,n.publicError)(`No enabled bot named "${d}".`),d=a.name}let e=await (0,t.sendRoomMessage)(a,{...c,to:d});return z(a.threadId).catch(a=>m.logger.error("room message scheduling",a)),e},emit:async g=>{(!b.aborted||"tool-result"===g.type)&&(await c.on(g),"step"===g.type&&await (0,v.addThreadUsage)(a.threadId,g.usage,a.bot===f.bot?{tokens:g.usage.input,budget:g.budget}:null),"compact"===g.type&&await (0,v.addThreadUsage)(a.threadId,g.usage),"turn-end"===g.type&&(d=g),"error"===g.type&&(e={message:g.message,retry:g.retry},g.budget&&await (0,t.lowerRoomContextBudget)(a,g.budget)))}})}catch(c){b.aborted||(m.logger.error(`thread ${a.threadId}: ${a.bot} broke`,c),e={message:(0,g.modelErrorToString)(c),retry:!(0,n.isPublicError)(c)&&!(0,g.isProviderRefusal)(c)})}return{ending:d,failure:e}}class Q{work;signal;lane;assistant;tool;parts;calls;results;constructor(a,b){this.work=a,this.signal=b,this.lane=(0,p.PromiseChain)(),this.assistant=null,this.tool=null,this.parts={assistant:[],tool:[]},this.calls=new Set,this.results=new Set}async write(a,b,c=!1){let d={bot:this.work.bot,parent:this.work.id,role:b.role,content:b.content,compact:c,note:c};return null===a?(0,t.appendRoomMessage)(this.work.threadId,d):(await (0,v.upsertMessage)(this.work.threadId,a,d),a)}on(a){return this.lane(async()=>{if(!this.signal.aborted||"tool-result"===a.type)if("text"===a.type)this.parts.assistant.push({type:"text",text:a.text}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant});else if("tool"===a.type){if(this.calls.has(a.id)){let b=this.parts.assistant.find(b=>"tool-call"===b.type&&b.toolCallId===a.id);b&&"tool-call"===b.type&&a.providerOptions&&(b.providerOptions=a.providerOptions,this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant}));return}this.calls.add(a.id),this.parts.assistant.push({type:"tool-call",toolCallId:a.id,toolName:a.name,input:a.input,...a.providerExecuted?{providerExecuted:!0}:{},...a.providerOptions?{providerOptions:a.providerOptions}:{}}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant})}else if("tool-result"===a.type){if(this.results.has(a.id))return;this.results.add(a.id),this.parts.tool.push({type:"tool-result",toolCallId:a.id,toolName:a.name,output:a.error?{type:"error-text",value:String(a.output)}:"string"==typeof a.output?{type:"text",value:a.output}:{type:"json",value:a.output}}),this.tool=await this.write(this.tool,{role:"tool",content:this.parts.tool})}else if("step"===a.type){let b=[this.assistant,this.tool];for(let[c,d]of a.messages.entries())await this.write(b[c]??null,d);let c=b.slice(a.messages.length).filter(a=>null!==a);c.length&&await (0,v.deleteMessages)(this.work.threadId,c),this.assistant=this.tool=null,this.parts={assistant:[],tool:[]}}else"compact"===a.type&&await this.write(null,{role:"user",content:a.text},!0)})}}async function C(a){let b=[...L.values()].filter(b=>b.threadId===a);for(let a of b)a.stop.abort();await Promise.all(b.map(a=>a.done))}async function D(a){await M(a,async()=>{let b=await (0,v.findThread)(a);b||(0,n.publicError)("No such thread."),b.endedAt&&(0,n.publicError)("That thread has already ended."),await (0,t.cancelRoom)(a),await (0,v.updateThread)(a,{status:"cancelled",outcome:null,pending:null,seen:!0,endedAt:new Date}),await C(a),await (0,k.closeJobShell)(a)})}async function E(a){return M(a,()=>F(a))}async function F(a){let b=await (0,v.findThread)(a);await (0,t.cancelRoom)(a),await C(a),await (0,k.removeJobBrowsers)(a);let c=await (0,v.deleteThread)(a);return c&&b&&await (0,k.removeJobScratch)(a,b.label),c}async function G(){let a=0;for(let b of(await (0,v.listThreadFolders)()))("done"===b.status||"cancelled"===b.status)&&await M(b.id,async()=>{let c=await (0,v.findThread)(b.id);(c?.status==="done"||c?.status==="cancelled")&&await F(b.id)&&(a+=1)});return a}async function H(){let a=Date.now()-f.WORKSPACE_KEEP.forMs,b=b=>("done"===b.status||"cancelled"===b.status)&&(b.endedAt??b.updatedAt).getTime()<a,c=new Set(await (0,k.listScratchFolders)()),d=[];for(let a of(await (0,v.listThreadFolders)())){let e=(0,k.jobScratch)(a.id,a.label);c.delete(e)&&b(a)&&await M(a.id,async()=>{let c=await (0,v.findThread)(a.id);c&&b(c)&&(await (0,k.closeHiddenBrowser)(a.id),await (0,k.removeJobScratch)(a.id,a.label),d.push(e))})}return d.push(...await (0,k.removeUnchangedFolders)([...c])),await (0,k.pruneJobFiles)(),d.length&&m.logger.info(`cleared ${d.length} old job folder(s): ${d.join(", ")}`),d}async function I(){for(let a of(await (0,v.listRunningThreadIds)()))await M(a,async()=>{[...L.values()].some(b=>b.threadId===a)||(await (0,v.findThread)(a))?.status==="running"&&await (0,t.pauseRoom)(a,"The server restarted. Resume from the saved conversation.")})}async function J(a,b=!1){let c=(async()=>{let c=await (0,v.listRunningThreadIds)();await Promise.all(c.map(c=>M(c,async()=>{(await (0,v.findThread)(c))?.status==="running"&&(await C(c),await (0,t.pauseRoom)(c,a,b))})))})();N.current=c,await c}async function K(){if(await N.current,e.presence.watching)for(let a of(await (0,v.listAutoStoppedThreads)()))await M(a,async()=>{let b=await (0,v.findThread)(a);b?.status==="waiting"&&b.pending?.auto&&await (0,t.resumeRoom)(a,!1)}),await z(a)}a.s(["answerThread",0,y,"askCompact",0,function(a,b){O.add(P(a,b))},"cancelThread",0,D,"pauseThreads",0,J,"removeFinishedThreads",0,G,"removeThread",0,E,"resumeStoppedThreads",0,K,"startThread",0,x,"sweepJobFiles",0,H,"sweepThreads",0,I]),c()}catch(a){c(a)}},!1),317844,a=>a.a(async(b,c)=>{try{var d,e=a.i(106450),f=a.i(64203),g=a.i(569572),h=a.i(176668),i=a.i(182248),j=a.i(947950),k=a.i(899284),l=b([j]);[j]=l.then?(await l)():l;class m extends Error{serverName;authorizationUrl;constructor(a,b){super(`MCP server "${a}" requires authorization`),this.serverName=a,this.authorizationUrl=b,this.name="McpAuthRequiredError"}}class n{store;serverName;oauth;callbackUrl;clientName;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"}],g=f.filter(a=>!a.path.endsWith("/")).map(a=>a.path),h=f.filter(a=>a.path.endsWith("/")).map(a=>a.path.slice(0,-1)),i=RegExp(`^(?:${g.join("|")}|(?:${h.join("|")})/.+)$`),j=["profile","preferences"];a.s(["MEMORY_ALWAYS_LISTED",0,j,"MEMORY_PATHS",0,f,"appNoteLine",0,a=>f.find(b=>b.path===a)?.of??null,"isAlwaysListed",0,a=>j.includes(a),"isMemoryPath",0,a=>i.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)}])},780946,a=>a.a(async(b,c)=>{try{var d=a.i(93321),e=a.i(258261),f=a.i(530385),g=a.i(203469),h=a.i(569572),i=a.i(184838),j=a.i(714428),k=a.i(221214),l=a.i(293480),m=a.i(643020),n=b([i,k]);[i,k]=n.then?(await n)():n;let z=()=>g.appEvents.emit({type:"routines"});async function o(a,b){return i.database.select({id:j.threadTable.id,status:j.threadTable.status,outcome:j.threadTable.outcome,updatedAt:j.threadTable.updatedAt}).from(j.threadTable).where((0,d.eq)(j.threadTable.routineId,a)).orderBy((0,f.desc)(j.threadTable.createdAt)).limit(b)}let A=async a=>{let{createdAt:b,...c}=a;return{...c,runs:await o(a.id,h.ROUTINE.runsShown)}};async function p(){let a=await i.database.select().from(j.routineTable).orderBy(j.routineTable.createdAt);return Promise.all(a.map(A))}async function q(a){let[b]=await i.database.select().from(j.routineTable).where((0,d.eq)(j.routineTable.id,a));return b?A(b):null}async function r(a){let b=await q(a.trim());if(b)return b;let c=a.trim().toLowerCase(),d=(await p()).filter(a=>a.label.toLowerCase()===c);return 1===d.length?d[0]:null}async function s(a){let b=await (0,k.findJobBot)(a);return(!b||b.disabled)&&(0,l.publicError)("Choose an enabled bot."),b.name}function t(a,b){b&&"once"===a.kind&&(0,m.momentOf)(a.at)<=new Date&&(0,l.publicError)("That time has passed. Pick a later one.")}async function u(a){let[{total:b}]=await i.database.select({total:(0,e.count)()}).from(j.routineTable);b>=h.ROUTINE.max&&(0,l.publicError)(`There are already ${h.ROUTINE.max} routines. Delete one to make another.`),t(a.schedule,!0);let[c]=await i.database.insert(j.routineTable).values({id:crypto.randomUUID(),...a,bot:await s(a.bot),nextRunAt:(0,m.nextRun)(a.schedule,new Date)}).returning();return z(),A(c)}async function v(a,b){let[c]=await i.database.select().from(j.routineTable).where((0,d.eq)(j.routineTable.id,a));if(!c)return null;let e=b.schedule??c.schedule,f=!!b.schedule||b.enabled&&!c.enabled;f&&t(e,b.enabled??c.enabled);let[g]=await i.database.update(j.routineTable).set({...b,...b.bot?{bot:await s(b.bot)}:{},...f?{nextRunAt:(0,m.nextRun)(e,new Date)}:{}}).where((0,d.eq)(j.routineTable.id,a)).returning();return z(),A(g)}async function w(a){let b=await i.database.delete(j.routineTable).where((0,d.eq)(j.routineTable.id,a)).returning({id:j.routineTable.id});return b.length&&z(),b.length>0}async function x(a){return(await o(a,1))[0]??null}async function y(a){return(await i.database.select({id:j.threadTable.id}).from(j.threadTable).where((0,d.and)((0,d.eq)(j.threadTable.routineId,a),(0,d.eq)(j.threadTable.seen,!1),(0,d.inArray)(j.threadTable.status,["done","cancelled"])))).map(a=>a.id)}a.s(["createRoutine",0,u,"deleteRoutine",0,w,"findRoutine",0,q,"latestRun",0,x,"listRoutines",0,p,"listUnseenRunIds",0,y,"resolveRoutine",0,r,"updateRoutine",0,v]),c()}catch(a){c(a)}},!1),643020,a=>{"use strict";var b=a.i(723885),c=a.i(569572),d=a.i(706210);let e=b.default.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"A time is HH:MM, 00:00 to 23:59");function f(a){let[b,c]=a.split(" "),[d,e,f]=b.split("-").map(Number),[g,h]=c.split(":").map(Number);return new Date(d,e-1,f,g,h)}let g=/^\d{4}-\d\d-\d\d ([01]\d|2[0-3]):[0-5]\d$/,h=b.default.string().regex(g,'A moment is "YYYY-MM-DD HH:MM"').refine(a=>{if(!g.test(a))return!0;let b=f(a);return b.getMonth()===Number(a.slice(5,7))-1&&b.getDate()===Number(a.slice(8,10))},"There is no such day"),i=b.default.discriminatedUnion("kind",[b.default.object({kind:b.default.literal("once"),at:h}),b.default.object({kind:b.default.literal("daily"),time:e,days:b.default.array(b.default.number().int().min(1).max(7)).min(1,"Pick at least one day").transform(a=>[...new Set(a)].sort((a,b)=>a-b))}),b.default.object({kind:b.default.literal("every"),hours:b.default.number().int().min(c.ROUTINE.minHours,`No more often than every ${c.ROUTINE.minHours}h`).max(168)})]),j=b.default.object({bot:b.default.string().trim().min(1,"Pick a bot"),label:b.default.string().trim().min(1,"Give it a name").max(80),request:b.default.string().trim().min(1,"Say what it should do"),schedule:i}),k=b.default.object({id:b.default.string(),status:b.default.enum(["running","waiting","done","cancelled"]),outcome:b.default.string().nullable(),updatedAt:d.DateLikeSchema});j.extend({id:b.default.string(),enabled:b.default.boolean(),nextRunAt:d.DateLikeSchema,runs:b.default.array(k)});let l=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],m=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];a.s(["RoutineInputSchema",0,j,"RoutineScheduleSchema",0,i,"momentOf",0,f,"nextRun",0,function(a,b){if("once"===a.kind)return f(a.at);if("every"===a.kind)return new Date(b.getTime()+36e5*a.hours);let[c,d]=a.time.split(":").map(Number);for(let e=0;e<=7;e++){let f=new Date(b);f.setDate(f.getDate()+e),f.setHours(c,d,0,0);let g=0===f.getDay()?7:f.getDay();if(f>b&&a.days.includes(g))return f}return new Date(b.getTime()+864e5)},"scheduleText",0,function(a){if("once"===a.kind){let[b,c]=a.at.split(" "),[,d,e]=b.split("-").map(Number);return`Once \xb7 ${m[d-1]} ${e} ${c}`}if("every"===a.kind)return 1===a.hours?"Every hour":`Every ${a.hours} hours`;let{days:b,time:c}=a;if(7===b.length)return`Daily ${c}`;if(1===b.length)return`${l[b[0]-1]} ${c}`;let d=b.every((a,c)=>0===c||a===b[c-1]+1)?`${l[b[0]-1]}–${l[b.at(-1)-1]}`:b.map(a=>l[a-1]).join(" ");return`Daily ${c} \xb7 ${d}`}])},487591,422807,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(203469),e=a.i(569572);a.i(821415),a.i(176668);let f=a=>a.trim().toLowerCase().replace(/^[a-z]+:\/\//,"").replace(/^www\./,"").replace(/[/?#].*$/,"");a.s(["siteOf",0,f],422807);let g=(0,c.join)(e.DATA_DIR,e.PATHS.signIns),h=a=>(0,c.join)(g,`${encodeURIComponent(f(a))}.json`),i=()=>d.appEvents.emit({type:"signins"});async function j(a){try{return JSON.parse(await (0,b.readFile)(h(a),"utf8"))}catch{return null}}async function k(a){await (0,b.mkdir)(g,{recursive:!0}),await (0,b.writeFile)(h(a.site),JSON.stringify(a),{mode:384}),i()}async function l(){let a=await (0,b.readdir)(g).catch(()=>[]);return(await Promise.all(a.filter(a=>a.endsWith(".json")).map(a=>j(decodeURIComponent(a.slice(0,-5)))))).flatMap(a=>a?[(({state:a,...b})=>b)(a)]:[]).sort((a,b)=>a.site.localeCompare(b.site))}async function m(a){let b=f(a.site),c=await j(b),d={site:b,account:a.account.trim()||b,bots:[...new Set([...c?.bots??[],a.bot])],asking:(c?.asking??[]).filter(b=>b!==a.bot),keptAt:new Date().toISOString(),usedAt:c?.usedAt??null,state:a.state};return await k(d),(({state:a,...b})=>b)(d)}async function n(a,b){let c=await j(a);if(!c)return{kind:"none",kept:(await l()).map(a=>a.site)};if(!c.bots.includes(b))return c.asking.includes(b)||await k({...c,asking:[...c.asking,b]}),{kind:"ask",signIn:(({state:a,...b})=>b)(c)};let d={...c,usedAt:new Date().toISOString()};return await k(d),{kind:"state",signIn:(({state:a,...b})=>b)(d),state:c.state}}async function o(a,b,c){let d=await j(a);d&&await k({...d,bots:c?[...new Set([...d.bots,b])]:d.bots.filter(a=>a!==b),asking:d.asking.filter(a=>a!==b)})}async function p(a){await (0,b.rm)(h(a),{force:!0}),i()}a.s(["borrowSignIn",0,n,"keepSignIn",0,m,"removeSignIn",0,p,"setSignInBot",0,o],487591)},138100,a=>{"use strict";var b=a.i(912714),c=a.i(750227),d=a.i(569572),e=a.i(821415),f=a.i(176668),g=a.i(182248),h=a.i(762805);let i=(0,c.join)(d.APP_DIR,d.PATHS.skills.default),j=(0,c.join)(d.DATA_DIR,d.PATHS.skills.custom),k=a=>(0,c.join)(e.WORKSPACE,(0,e.botFolder)(a),d.PATHS.skills.own);async function l(a,e){let f=(0,c.join)(d.APP_DIR,d.PATHS.skills.seeds,a.toLowerCase());await (0,b.cp)(f,k(e),{recursive:!0,force:!1}).catch(a=>{if("ENOENT"!==a.code)throw a})}async function m(a,b){let c=[],d=new Set;for(let e of b){let b;try{b=await a.readdir(e,{withFileTypes:!0})}catch{continue}for(let i of b){let b,j;if(!i.isDirectory())continue;let k=`${e}/${i.name}`,l=`${k}/SKILL.md`;try{b=await a.readFile(l,"utf-8")}catch{continue}try{j=(0,h.parseFrontmatter)(b)}catch(a){f.logger.warn(`skill ${k}: SKILL.md front matter did not load — ${(0,g.errorToString)(a)}`);continue}!(!(0,h.runsHere)(j)||d.has(j.name))&&(d.add(j.name),j.disabled||c.push({name:j.name,description:j.description,path:k}))}}return c}a.s(["giveSeedSkills",0,l,"loadSkills",0,(a,b)=>m(a,b?[i,k(b),j]:[i,j])])},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(),platforms:f.z.array(f.z.string()).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`---
|
|
117
119
|
${(0,d.stringify)(a).trim()}
|
|
118
120
|
---
|
|
119
121
|
|
|
120
122
|
${b.trim()}
|
|
121
|
-
`},"setSkillDisabled",0,r,"splitFrontmatter",0,o,"writeCustomSkill",0,t],762805)},626550,a=>{"use strict";var b=a.i(762008);let c={[b.TOOL_NAMES.memory_recall]:"Checking your notes",[b.TOOL_NAMES.memory_remember]:"Noting that down",[b.TOOL_NAMES.memory_forget]:"Forgetting that",[b.TOOL_NAMES.bash]:"Doing it on this computer",[b.TOOL_NAMES.web_search]:"Searching the web",[b.TOOL_NAMES.load_skill]:"Reading how to do this",[b.TOOL_NAMES.look_at]:"Looking at the picture",[b.TOOL_NAMES.end_call]:"Ending the call"};a.s(["searchOf",0,function(a,c){if(a!==b.TOOL_NAMES.web_search)return null;try{let a=JSON.parse(c),b=Array.isArray(a.sources)?a.sources.flatMap(a=>a&&"object"==typeof a&&"string"==typeof a.url?[a]:[]):[];return{query:"string"==typeof a.query?a.query:null,sources:b}}catch{return null}},"startedLabel",0,function(a,c){if(a!==b.TOOL_NAMES.thread_start)return null;try{let a=JSON.parse(c);return"string"==typeof a.label?a.label:null}catch{return null}},"toolLine",0,function(a,d){let
|
|
123
|
+
`},"runsHere",0,({platforms:a})=>!a||a.includes(process.platform),"setSkillDisabled",0,r,"splitFrontmatter",0,o,"writeCustomSkill",0,t],762805)},626550,a=>{"use strict";var b=a.i(762008);let c={[b.TOOL_NAMES.memory_recall]:"Checking your notes",[b.TOOL_NAMES.memory_remember]:"Noting that down",[b.TOOL_NAMES.memory_forget]:"Forgetting that",[b.TOOL_NAMES.memory_conversation]:"Reading back an earlier call",[b.TOOL_NAMES.bash]:"Doing it on this computer",[b.TOOL_NAMES.web_search]:"Searching the web",[b.TOOL_NAMES.load_skill]:"Reading how to do this",[b.TOOL_NAMES.look_at]:"Looking at the picture",[b.TOOL_NAMES.end_call]:"Ending the call",[b.TOOL_NAMES.routine]:"Checking your routines"};b.TOOL_NAMES.thread_tell,b.TOOL_NAMES.thread_answer,b.TOOL_NAMES.thread_status,b.TOOL_NAMES.thread_show,b.TOOL_NAMES.thread_cancel,b.TOOL_NAMES.thread_seen,a.s(["searchOf",0,function(a,c){if(a!==b.TOOL_NAMES.web_search)return null;try{let a=JSON.parse(c),b=Array.isArray(a.sources)?a.sources.flatMap(a=>a&&"object"==typeof a&&"string"==typeof a.url?[a]:[]):[];return{query:"string"==typeof a.query?a.query:null,sources:b}}catch{return null}},"startedLabel",0,function(a,c){if(a!==b.TOOL_NAMES.thread_start)return null;try{let a=JSON.parse(c);return"string"==typeof a.label?a.label:null}catch{return null}},"toolLine",0,function(a,d,e=null){let f;if(a===b.TOOL_NAMES.tool_search||a===b.TOOL_NAMES.tool_call)return"Reaching a connected service";let g=function(a){if(!a)return null;try{let b=JSON.parse(a);if(b&&"object"==typeof b&&!Array.isArray(b))return b}catch{}return null}(d);return(g&&function(a,c,d){if(a===b.TOOL_NAMES.memory_remember){let a="string"==typeof c.path?c.path.trim():"",b=function(a){if(!Array.isArray(a.facts))return null;let b=a.facts.map(a=>a&&"object"==typeof a&&"string"==typeof a.text?a.text.trim():"").filter(Boolean);return b.length?{text:b[0],more:b.length-1}:null}(c);if(!a)return null;if(!b)return`Noting that under ${a}`;let d=b.more>0?` (+${b.more})`:"";return`Noting under ${a}: ${function(a){let b=a.trim().replace(/\s+/g," ");if(b.length<=28)return b;let c=b.slice(0,28),d=c.lastIndexOf(" ");return`${(d>14?c.slice(0,d):c).trimEnd()}…`}(b.text)}${d}`}if(a===b.TOOL_NAMES.thread_start){let a="string"==typeof c.bot?c.bot.trim():"";return a?`Handing this to ${a}`:"Handing this over"}if(a===b.TOOL_NAMES.web_search){let a="string"==typeof c.query?c.query.trim():"";return a?`Searching \xb7 ${a}`:null}if(a===b.TOOL_NAMES.routine){if("create"===c.action){let a=["string"==typeof c.bot?c.bot.trim():"",function(a){if("string"==typeof a.at&&a.at.length>=16){let[b,c]=a.at.split(" "),[d,e,f]=b.split("-").map(Number),g=new Date(d,e-1,f);if(g.toDateString()===new Date().toDateString())return`once at ${c}`;let h=g.toLocaleDateString("en-US",{month:"short",day:"numeric"});return`once, ${h} ${c}`}return"string"==typeof a.time&&a.time?`daily at ${a.time}`:"number"==typeof a.everyHours?`every ${a.everyHours} hours`:null}(c)].filter(Boolean).join(", ");return a?`Setting a routine \xb7 ${a}`:"Setting a routine"}return"change"===c.action?"Changing a routine":"delete"===c.action?"Deleting a routine":null}let e="string"==typeof c.thread?c.thread.trim():"";return a===b.TOOL_NAMES.thread_tell?d?`Telling ${d}`:"Passing that on":a===b.TOOL_NAMES.thread_answer?d?`Answering ${d}`:"Answering that":a===b.TOOL_NAMES.thread_cancel?e?`Stopping ${e}`:"Stopping that":a===b.TOOL_NAMES.thread_seen?e?`Marking ${e} as read`:"Marking that as read":a===b.TOOL_NAMES.thread_show?e?`Opening ${e}`:"Opening that":a===b.TOOL_NAMES.thread_status?e&&"all"!==e.toLowerCase()?`Checking on ${e}`:"Checking on the work":null}(a,g,e))??c[a]??((f=a.indexOf("__"))<=0?null:`Reaching ${a.slice(0,f).replace(/[-_]/g," ")}`)}])},956802,a=>{"use strict";var b=a.i(874533),c=a.i(569572);let d=`on run argv
|
|
122
124
|
display notification (item 2 of argv) with title (item 1 of argv)
|
|
123
125
|
end run`,e=`
|
|
124
126
|
$ErrorActionPreference = 'Stop'
|
|
@@ -250,4 +252,4 @@ ${b}`:c}else{let a=e.commentBefore;e.commentBefore=a?`${c}
|
|
|
250
252
|
${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}
|
|
251
253
|
${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}];
|
|
252
254
|
|
|
253
|
-
//# sourceMappingURL=
|
|
255
|
+
//# sourceMappingURL=_1d423aj._.js.map
|