thursday-agent 0.9.0 → 0.11.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.
Files changed (320) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +0 -1
  3. package/.next/build-manifest.json +3 -3
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/routes-manifest.json +0 -6
  6. package/.next/server/app/_global-error/page.js.nft.json +1 -1
  7. package/.next/server/app/_global-error.html +1 -1
  8. package/.next/server/app/_global-error.rsc +1 -1
  9. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  12. package/.next/server/app/_not-found/page.js.nft.json +1 -1
  13. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  14. package/.next/server/app/_not-found.html +1 -1
  15. package/.next/server/app/_not-found.rsc +2 -2
  16. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  17. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  18. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  19. package/.next/server/app/api/artifact/route.js.nft.json +1 -1
  20. package/.next/server/app/api/bot/keep-working/route.js.nft.json +1 -1
  21. package/.next/server/app/api/bot/memory/files/route.js.nft.json +1 -1
  22. package/.next/server/app/api/bot/memory/route.js.nft.json +1 -1
  23. package/.next/server/app/api/bot/route.js.nft.json +1 -1
  24. package/.next/server/app/api/bot/thread/[id]/route.js.nft.json +1 -1
  25. package/.next/server/app/api/bot/thread/route.js.nft.json +1 -1
  26. package/.next/server/app/api/config/route.js.nft.json +1 -1
  27. package/.next/server/app/api/events/route.js.nft.json +1 -1
  28. package/.next/server/app/api/favicon/[host]/route.js.nft.json +1 -1
  29. package/.next/server/app/api/file/[...path]/route.js.nft.json +1 -1
  30. package/.next/server/app/api/llm-model/catalog/route.js.nft.json +1 -1
  31. package/.next/server/app/api/llm-model/credits/route.js.nft.json +1 -1
  32. package/.next/server/app/api/llm-model/route.js.nft.json +1 -1
  33. package/.next/server/app/api/llm-model/subscription/route.js.nft.json +1 -1
  34. package/.next/server/app/api/mcp/[name]/route.js.nft.json +1 -1
  35. package/.next/server/app/api/mcp/oauth/callback/route.js.nft.json +1 -1
  36. package/.next/server/app/api/mcp/route.js.nft.json +1 -1
  37. package/.next/server/app/api/mcp/tools/route.js.nft.json +1 -1
  38. package/.next/server/app/api/memory/edit/route.js.nft.json +1 -1
  39. package/.next/server/app/api/memory/route.js.nft.json +1 -1
  40. package/.next/server/app/api/reach/route.js +13 -13
  41. package/.next/server/app/api/reach/route.js.nft.json +1 -1
  42. package/.next/server/app/api/routine/route.js.nft.json +1 -1
  43. package/.next/server/app/api/signins/route.js +1 -1
  44. package/.next/server/app/api/signins/route.js.nft.json +1 -1
  45. package/.next/server/app/api/skills/[source]/[name]/route.js.nft.json +1 -1
  46. package/.next/server/app/api/skills/route.js.nft.json +1 -1
  47. package/.next/server/app/api/thursday/call/route.js.nft.json +1 -1
  48. package/.next/server/app/api/thursday/skills/route.js.nft.json +1 -1
  49. package/.next/server/app/api/thursday/text/route.js.nft.json +1 -1
  50. package/.next/server/app/api/thursday/tool-call/route.js +14 -15
  51. package/.next/server/app/api/thursday/tool-call/route.js.nft.json +1 -1
  52. package/.next/server/app/api/workspace/files/route.js.nft.json +1 -1
  53. package/.next/server/app/api/workspace/route.js.nft.json +1 -1
  54. package/.next/server/app/artifact/[...path]/page/server-reference-manifest.json +1 -1
  55. package/.next/server/app/artifact/[...path]/page.js.nft.json +1 -1
  56. package/.next/server/app/artifact/[...path]/page_client-reference-manifest.js +1 -1
  57. package/.next/server/app/favicon.ico/route.js.nft.json +1 -1
  58. package/.next/server/app/manifest.webmanifest/route.js.nft.json +1 -1
  59. package/.next/server/app/page/server-reference-manifest.json +56 -56
  60. package/.next/server/app/page.js +4 -4
  61. package/.next/server/app/page.js.nft.json +1 -1
  62. package/.next/server/app/page_client-reference-manifest.js +1 -1
  63. package/.next/server/app-paths-manifest.json +0 -1
  64. package/.next/server/chunks/[root-of-the-server]__014ydvq._.js +2 -2
  65. package/.next/server/chunks/[root-of-the-server]__0209ah4._.js +7 -5
  66. package/.next/server/chunks/[root-of-the-server]__04r4h-2._.js +4 -2
  67. package/.next/server/chunks/[root-of-the-server]__0542v_d._.js +3 -0
  68. package/.next/server/chunks/[root-of-the-server]__0gewdg9._.js +2 -2
  69. package/.next/server/chunks/[root-of-the-server]__0mrk2it._.js +1 -1
  70. package/.next/server/chunks/[root-of-the-server]__1-swlkw._.js +2 -2
  71. package/.next/server/chunks/[root-of-the-server]__12iddfq._.js +1 -1
  72. package/.next/server/chunks/[root-of-the-server]__1ai5lme._.js +3 -3
  73. package/.next/server/chunks/[root-of-the-server]__1cjxw0-._.js +2 -2
  74. package/.next/server/chunks/{[root-of-the-server]__1fy2g82._.js → [root-of-the-server]__1k3j52n._.js} +1 -1
  75. package/.next/server/chunks/[root-of-the-server]__1kyjt5m._.js +3 -3
  76. package/.next/server/chunks/[root-of-the-server]__1ygplx1._.js +1 -1
  77. package/.next/server/chunks/_05v8k21._.js +3 -1
  78. package/.next/server/chunks/_0awtznl._.js +1 -1
  79. package/.next/server/chunks/_0na2fj1._.js +1 -1
  80. package/.next/server/chunks/_0x-ej3f._.js +17 -17
  81. package/.next/server/chunks/_12-amdu._.js +2 -2
  82. package/.next/server/chunks/_15740dw._.js +60 -0
  83. package/.next/server/chunks/_1dc_d1q._.js +3 -3
  84. package/.next/server/chunks/_1i350l5._.js +3 -1
  85. package/.next/server/chunks/_1jc5g4p._.js +2 -2
  86. package/.next/server/chunks/_1jn-aep._.js +4 -4
  87. package/.next/server/chunks/_1m88lkh._.js +11 -11
  88. package/.next/server/chunks/_1ogqovh._.js +4 -4
  89. package/.next/server/chunks/_1uuucy-._.js +1 -1
  90. package/.next/server/chunks/_1zxp-p6._.js +1 -1
  91. package/.next/server/chunks/features_0rfvely._.js +5 -3
  92. package/.next/server/chunks/ssr/{[root-of-the-server]__1se25x0._.js → [root-of-the-server]__0hpp3nw._.js} +29 -13
  93. package/.next/server/chunks/ssr/[root-of-the-server]__0m7u9j-._.js +3 -0
  94. package/.next/server/chunks/ssr/[root-of-the-server]__0tzekbl._.js +24 -60
  95. package/.next/server/chunks/ssr/[root-of-the-server]__1cz2rz5._.js +3 -0
  96. package/.next/server/chunks/ssr/{[root-of-the-server]__0tvavy9._.js → [root-of-the-server]__1iwyp1e._.js} +1 -1
  97. package/.next/server/chunks/ssr/[root-of-the-server]__1w9hqq8._.js +1 -1
  98. package/.next/server/chunks/ssr/_097-ljd._.js +1 -1
  99. package/.next/server/chunks/ssr/{_1tmu8z-._.js → _0btzccu._.js} +2 -2
  100. package/.next/server/chunks/ssr/_0fqhhwi._.js +1 -1
  101. package/.next/server/chunks/ssr/_0hjzb5o._.js +3 -0
  102. package/.next/server/chunks/ssr/_0ld9_qq._.js +1 -1
  103. package/.next/server/chunks/ssr/{_0urj3mc._.js → _0ouzu9f._.js} +2 -2
  104. package/.next/server/chunks/ssr/{_1-zyvdb._.js → _0u7ko71._.js} +2 -2
  105. package/.next/server/chunks/ssr/{_0ltz2q5._.js → _0wd_o8-._.js} +2 -2
  106. package/.next/server/chunks/ssr/_0ya0cb0._.js +3 -0
  107. package/.next/server/chunks/ssr/_10yyqtk._.js +67 -0
  108. package/.next/server/chunks/ssr/{_1uy0xom._.js → _12eyown._.js} +3 -3
  109. package/.next/server/chunks/ssr/_12mijol._.js +11 -11
  110. package/.next/server/chunks/ssr/_132qkfz._.js +1 -1
  111. package/.next/server/chunks/ssr/_184327j._.js +1 -1
  112. package/.next/server/chunks/ssr/{_1z74dmq._.js → _19ps4p3._.js} +7 -7
  113. package/.next/server/chunks/ssr/{_1flbs77._.js → _1bhy4yg._.js} +2 -2
  114. package/.next/server/chunks/ssr/_1d423aj._.js +7 -5
  115. package/.next/server/chunks/ssr/{_1a-nuxx._.js → _1kd843u._.js} +2 -2
  116. package/.next/server/chunks/ssr/{_0ital-2._.js → _1kq2ye_._.js} +2 -2
  117. package/.next/server/chunks/ssr/_1mqn9mc._.js +1 -1
  118. package/.next/server/chunks/ssr/_1neoj22._.js +1 -1
  119. package/.next/server/chunks/ssr/_1p8xorg._.js +3 -0
  120. package/.next/server/chunks/ssr/{_1x-kojb._.js → _1q683w8._.js} +3 -3
  121. package/.next/server/chunks/ssr/_1tawxu2._.js +3 -0
  122. package/.next/server/chunks/ssr/{_0scf7xy._.js → _1w2oba6._.js} +2 -2
  123. package/.next/server/chunks/ssr/_1xoch6f._.js +1 -1
  124. package/.next/server/chunks/ssr/{_0kjj5ts._.js → _1ybo1hd._.js} +3 -3
  125. package/.next/server/chunks/ssr/features_bot_0s11m4r._.js +3 -0
  126. package/.next/server/chunks/ssr/features_connectors_components_mcp-setting_tsx_0jmbgvp._.js +1 -1
  127. package/.next/server/chunks/ssr/features_memory_components_memory-setting_tsx_0oa43sw._.js +1 -1
  128. package/.next/server/chunks/ssr/features_routine_components_routine-setting_tsx_055fknz._.js +1 -1
  129. package/.next/server/chunks/ssr/features_workspace_00jz2hu._.js +1 -1
  130. package/.next/server/chunks/ssr/{node_modules_1af3w91._.js → node_modules_00pocul._.js} +1 -1
  131. package/.next/server/chunks/ssr/{node_modules_0th357h._.js → node_modules_02zt4az._.js} +1 -1
  132. package/.next/server/chunks/ssr/{node_modules_0jljel9._.js → node_modules_05ojmcl._.js} +1 -1
  133. package/.next/server/chunks/ssr/{node_modules_0wnlddw._.js → node_modules_06i6bli._.js} +1 -1
  134. package/.next/server/chunks/ssr/{node_modules_06bb4q8._.js → node_modules_09dj429._.js} +1 -1
  135. package/.next/server/chunks/ssr/{node_modules_068ws5v._.js → node_modules_0auzgvx._.js} +1 -1
  136. package/.next/server/chunks/ssr/{node_modules_1ogczzz._.js → node_modules_0evjwh1._.js} +1 -1
  137. package/.next/server/chunks/ssr/{node_modules_13kwejm._.js → node_modules_0gmdur8._.js} +1 -1
  138. package/.next/server/chunks/ssr/{node_modules_1s-gb-1._.js → node_modules_0j3te-1._.js} +1 -1
  139. package/.next/server/chunks/ssr/{node_modules_1bucjlk._.js → node_modules_0rbaymq._.js} +1 -1
  140. package/.next/server/chunks/ssr/{node_modules_1wbkzl9._.js → node_modules_0tf8_1e._.js} +1 -1
  141. package/.next/server/chunks/ssr/{node_modules_12et8d5._.js → node_modules_0yqy-0b._.js} +1 -1
  142. package/.next/server/chunks/ssr/{node_modules_1lkix61._.js → node_modules_1-53ebx._.js} +1 -1
  143. package/.next/server/chunks/ssr/{node_modules_03d0rfz._.js → node_modules_1-y9aho._.js} +1 -1
  144. package/.next/server/chunks/ssr/{node_modules_0x630an._.js → node_modules_11bltzp._.js} +1 -1
  145. package/.next/server/chunks/ssr/{node_modules_0uyh_vb._.js → node_modules_18jn2qo._.js} +1 -1
  146. package/.next/server/chunks/ssr/{node_modules_0dzm4um._.js → node_modules_1_te3bu._.js} +1 -1
  147. package/.next/server/chunks/ssr/{node_modules_07rs_p2._.js → node_modules_1c0pg3k._.js} +1 -1
  148. package/.next/server/chunks/ssr/{node_modules_0sgy-dc._.js → node_modules_1en2jx5._.js} +1 -1
  149. package/.next/server/chunks/ssr/{node_modules_0ubdtk-._.js → node_modules_1p-c8cr._.js} +1 -1
  150. package/.next/server/chunks/ssr/{node_modules_1z1lrbk._.js → node_modules_1qe-oxg._.js} +1 -1
  151. package/.next/server/chunks/ssr/{node_modules_04_sbbc._.js → node_modules_1rjt833._.js} +1 -1
  152. package/.next/server/chunks/ssr/{node_modules_0yvz9e0._.js → node_modules_1tzw5sn._.js} +1 -1
  153. package/.next/server/chunks/ssr/{node_modules_1uwg-gz._.js → node_modules_1x6uwvn._.js} +1 -1
  154. package/.next/server/chunks/ssr/{node_modules_0t_ez6-._.js → node_modules_1zqddke._.js} +1 -1
  155. package/.next/server/chunks/ssr/{node_modules_05ybmta._.js → node_modules_211zgim._.js} +1 -1
  156. package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0r443fh._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0y51bqj._.js} +1 -1
  157. package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_10wnlbk._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1sc114e._.js} +1 -1
  158. package/.next/server/middleware-build-manifest.js +3 -3
  159. package/.next/server/pages/404.html +1 -1
  160. package/.next/server/pages/500.html +1 -1
  161. package/.next/server/server-reference-manifest.js +1 -1
  162. package/.next/server/server-reference-manifest.json +57 -57
  163. package/.next/static/chunks/{13ixzheqw7o-w.js → 03-724sj0nk_z.js} +2 -2
  164. package/.next/static/chunks/03bhu4mk8en2q.js +1 -0
  165. package/.next/static/chunks/{3h2e-xv1zxh_f.js → 04imzjhvzw65d.js} +2 -2
  166. package/.next/static/chunks/{27tvv1i-smrck.js → 0gljzv9fz1g7d.js} +1 -1
  167. package/.next/static/chunks/{37j27b3e1gt7r.js → 0h0lythv1ql93.js} +1 -1
  168. package/.next/static/chunks/{2o4dndk0d68do.js → 0hzbj7f48cmx0.js} +1 -1
  169. package/.next/static/chunks/0lwunwbl7u7pt.js +1 -0
  170. package/.next/static/chunks/{0u9ae9k_2g7k3.js → 0r6nwxg4dv83t.js} +1 -1
  171. package/.next/static/chunks/0rn9nbg6aif9f.js +17 -0
  172. package/.next/static/chunks/{3bbzsitgiltnt.js → 0x_w4shtvrrfg.js} +1 -1
  173. package/.next/static/chunks/{2sdwbfs1x5skp.js → 0ympuji_ufypd.js} +1 -1
  174. package/.next/static/chunks/{3t9huugh-5_ps.js → 0zmrz4zfzm4dt.js} +1 -1
  175. package/.next/static/chunks/{0qmd8n52hp-6v.js → 11tlxkr7a_rpc.js} +1 -1
  176. package/.next/static/chunks/{2c64drdevdla3.js → 12scesro428m7.js} +2 -2
  177. package/.next/static/chunks/16s2fx3890_jd.js +65 -0
  178. package/.next/static/chunks/{0oyz95sujd2c7.js → 1qzfgplyo18tc.js} +1 -1
  179. package/.next/static/chunks/{04e-e--5lk26x.js → 1r4zajz14jp9-.js} +1 -1
  180. package/.next/static/chunks/1s6m4cmbn7htf.js +1 -0
  181. package/.next/static/chunks/1wl9t1-3i-q8p.css +1 -0
  182. package/.next/static/chunks/2-asot3p1j3yg.js +1 -0
  183. package/.next/static/chunks/{0u3ktztrzu1fa.js → 2-jn4xscbm-i2.js} +1 -1
  184. package/.next/static/chunks/22h9gvclqtx_2.js +1 -0
  185. package/.next/static/chunks/{337g9g_ux2gj-.js → 26-eblxwnykck.js} +1 -1
  186. package/.next/static/chunks/{43q9cgbuw8krx.js → 2kzwhbuobpkw3.js} +2 -2
  187. package/.next/static/chunks/2m6jd3586ijb-.js +1 -0
  188. package/.next/static/chunks/{0_awn8tucznxc.js → 304q9p54tcgm1.js} +1 -1
  189. package/.next/static/chunks/{1u5i-jti87jbo.js → 35wdx3wt7cg4a.js} +1 -1
  190. package/.next/static/chunks/37unh9460im7v.js +18 -0
  191. package/.next/static/chunks/{01xjer0i_e5z5.js → 39gj5vxz1zpm_.js} +1 -1
  192. package/.next/static/chunks/{427qsc6kahxyo.js → 39vrqy1r_00jc.js} +1 -1
  193. package/.next/static/chunks/{245hb85nsy6j4.js → 3dipmu0mptqum.js} +1 -1
  194. package/.next/static/chunks/3gki-squw28yu.js +1 -0
  195. package/.next/static/chunks/{3obf9n3cxj99k.js → 3jvldk2wvwbge.js} +1 -1
  196. package/.next/static/chunks/{38301ji-85i30.js → 3nnzdl_te20hv.js} +1 -1
  197. package/.next/static/chunks/{2m267diam_vib.js → 3tz4dr0_8pq1-.js} +1 -1
  198. package/.next/static/chunks/{2gocl3dq0_h1s.js → 3x6pggb-2kyrk.js} +1 -1
  199. package/.next/static/chunks/{025bmrgeukcb2.js → 4440mws9jz3mt.js} +1 -1
  200. package/README.md +4 -0
  201. package/app/api/thursday/tool-call/route.ts +1 -15
  202. package/components/ui/radio-group.tsx +2 -2
  203. package/docs/images/demo-still.jpg +0 -0
  204. package/docs/live-calls.md +19 -11
  205. package/features/ai/prompts/live.prompt.ts +51 -26
  206. package/features/ai/prompts/prompt-helper.ts +1 -9
  207. package/features/ai/prompts/thursday.prompt.ts +8 -2
  208. package/features/bot/bot.run.ts +9 -3
  209. package/features/bot/bot.seed.ts +35 -91
  210. package/features/bot/components/bot-room.tsx +0 -6
  211. package/features/bot/components/bot-setting.tsx +4 -4
  212. package/features/bot/components/room-pill.tsx +4 -2
  213. package/features/bot/seed-bots.ts +2 -2
  214. package/features/intro/components/intro.tsx +2 -3
  215. package/features/reach/reach.ts +2 -2
  216. package/features/routine/components/routine-setting.tsx +1 -1
  217. package/features/signins/signins.query.ts +66 -1
  218. package/features/thursday/components/side-captions.tsx +31 -8
  219. package/features/thursday/components/thursday-setting.tsx +5 -5
  220. package/features/thursday/components/thursday.tsx +97 -39
  221. package/features/thursday/components/write-line.tsx +28 -17
  222. package/features/thursday/thursday.action.ts +4 -20
  223. package/features/thursday/thursday.schema.ts +0 -9
  224. package/features/thursday/thursday.store.ts +11 -15
  225. package/features/thursday/thursday.text.ts +10 -8
  226. package/features/thursday/tool-line.ts +17 -6
  227. package/features/thursday/use-call-ring.ts +1 -5
  228. package/features/thursday/use-text-call.ts +37 -21
  229. package/features/thursday/use-thursday.ts +14 -44
  230. package/features/workspace/workspace.ts +4 -2
  231. package/guide/bots.md +13 -3
  232. package/guide/calls.md +7 -5
  233. package/knip.json +1 -0
  234. package/lib/live/live.session.ts +0 -39
  235. package/package.json +1 -1
  236. package/scripts/live-session.test.mts +19 -26
  237. package/seed-skills/analyst/README.md +18 -0
  238. package/seed-skills/analyst/data-report/SKILL.md +60 -0
  239. package/seed-skills/analyst/data-report/references/brief.md +31 -0
  240. package/seed-skills/analyst/data-report/references/company.md +41 -0
  241. package/seed-skills/analyst/data-report/references/comparison.md +42 -0
  242. package/seed-skills/analyst/data-report/references/decision.md +28 -0
  243. package/seed-skills/analyst/data-report/references/market-size.md +49 -0
  244. package/seed-skills/analyst/data-report/references/price-check.md +33 -0
  245. package/seed-skills/analyst/data-report/references/sources.md +51 -0
  246. package/seed-skills/analyst/data-report/references/trend.md +39 -0
  247. package/seed-skills/analyst/data-report/scripts/fetch.mjs +521 -0
  248. package/seed-skills/insta/instagram/SKILL.md +36 -0
  249. package/seed-skills/insta/instagram/references/dm.md +49 -0
  250. package/seed-skills/insta/instagram/references/post.md +74 -0
  251. package/seed-skills/insta/instagram/scripts/compose.mjs +333 -0
  252. package/seed-skills/insta/instagram/scripts/inbox.mjs +163 -0
  253. package/seed-skills/insta/instagram/scripts/lib.mjs +33 -0
  254. package/seed-skills/insta/instagram/scripts/media.mjs +104 -0
  255. package/seed-skills/insta/instagram/scripts/profile.mjs +143 -0
  256. package/seed-skills/insta/instagram/scripts/read.mjs +244 -0
  257. package/seed-skills/insta/instagram/scripts/search.mjs +137 -0
  258. package/seed-skills/insta/instagram/scripts/selectors.mjs +56 -0
  259. package/seed-skills/insta/instagram/scripts/sheet.mjs +43 -0
  260. package/seed-skills/insta/instagram/templates/carousel.html +62 -0
  261. package/seed-skills/marketer/README.md +6 -4
  262. package/seed-skills/marketer/copywriting/SKILL.md +1 -1
  263. package/seed-skills/marketer/emails/SKILL.md +1 -1
  264. package/seed-skills/marketer/launch/SKILL.md +1 -1
  265. package/seed-skills/marketer/product-marketing/SKILL.md +5 -5
  266. package/seed-skills/marketer/seo-audit/SKILL.md +1 -1
  267. package/seed-skills/marketer/social/SKILL.md +1 -1
  268. package/seed-skills/tutor/picture-book/SKILL.md +16 -0
  269. package/seed-skills/tutor/picture-book/book/book.css +181 -0
  270. package/seed-skills/tutor/picture-book/book/book.html +33 -0
  271. package/seed-skills/tutor/picture-book/book/book.js +60 -0
  272. package/seed-skills/tutor/picture-book/references/picture-book.md +104 -0
  273. package/seed-skills/tutor/picture-book/scripts/book-video.mjs +177 -0
  274. package/seed-skills/tutor/picture-book/scripts/book.mjs +98 -0
  275. package/skills/browser/SKILL.md +13 -4
  276. package/skills/browser/references/scripts.md +55 -0
  277. package/skills/browser/scripts/image-size.mjs +30 -0
  278. package/skills/browser/scripts/render.mjs +126 -0
  279. package/skills/browser/scripts/session.mjs +105 -0
  280. package/skills/browser/scripts/sheet.mjs +97 -0
  281. package/skills/browser/scripts/webimage.mjs +105 -0
  282. package/skills/interactive-page/SKILL.md +4 -3
  283. package/skills/interactive-page/scripts/chart.mjs +679 -0
  284. package/skills/interactive-page/scripts/page.mjs +1 -0
  285. package/.next/server/app/api/probe/route/app-paths-manifest.json +0 -3
  286. package/.next/server/app/api/probe/route/build-manifest.json +0 -12
  287. package/.next/server/app/api/probe/route/server-reference-manifest.json +0 -4
  288. package/.next/server/app/api/probe/route.js +0 -10
  289. package/.next/server/app/api/probe/route.js.map +0 -5
  290. package/.next/server/app/api/probe/route.js.nft.json +0 -1
  291. package/.next/server/app/api/probe/route_client-reference-manifest.js +0 -3
  292. package/.next/server/chunks/[root-of-the-server]__012s2o8._.js +0 -3
  293. package/.next/server/chunks/[root-of-the-server]__0z0hc1f._.js +0 -4
  294. package/.next/server/chunks/[root-of-the-server]__1v7-zke._.js +0 -5
  295. package/.next/server/chunks/_0whlpyi._.js +0 -4
  296. package/.next/server/chunks/_next-internal_server_app_api_probe_route_actions_0cqd30j.js +0 -3
  297. package/.next/server/chunks/ssr/[root-of-the-server]__0oo-wlv._.js +0 -103
  298. package/.next/server/chunks/ssr/[root-of-the-server]__0zuns7e._.js +0 -3
  299. package/.next/server/chunks/ssr/_070nv1_._.js +0 -3
  300. package/.next/server/chunks/ssr/_0dshsh4._.js +0 -3
  301. package/.next/server/chunks/ssr/_0l_mcfz._.js +0 -3
  302. package/.next/server/chunks/ssr/_0u5xv6g._.js +0 -3
  303. package/.next/server/chunks/ssr/_157yfrk._.js +0 -3
  304. package/.next/server/chunks/ssr/features_bot_1nr94ks._.js +0 -3
  305. package/.next/static/chunks/06nt9tatr-dug.js +0 -1
  306. package/.next/static/chunks/0ge-hx0ed83a1.js +0 -1
  307. package/.next/static/chunks/0pda_vf-abwvx.js +0 -1
  308. package/.next/static/chunks/0rowp9rx3qbxu.js +0 -18
  309. package/.next/static/chunks/1grkt5gr8pbg1.js +0 -17
  310. package/.next/static/chunks/1yugpvvi8qrbu.js +0 -101
  311. package/.next/static/chunks/27lkanxvtdn09.js +0 -1
  312. package/.next/static/chunks/3fec-aeteddr-.js +0 -1
  313. package/.next/static/chunks/3go3hwp1z2_h2.css +0 -1
  314. package/.next/static/chunks/3h2bun3hcggg8.js +0 -1
  315. package/.next/static/chunks/3j1y335o95mj7.js +0 -1
  316. package/lib/probe.server.ts +0 -17
  317. package/lib/probe.ts +0 -55
  318. /package/.next/static/{u8kJqShUAa49vY7BxAWsw → En1vUPazxcYjPjnnahcN5}/_buildManifest.js +0 -0
  319. /package/.next/static/{u8kJqShUAa49vY7BxAWsw → En1vUPazxcYjPjnnahcN5}/_clientMiddlewareManifest.js +0 -0
  320. /package/.next/static/{u8kJqShUAa49vY7BxAWsw → En1vUPazxcYjPjnnahcN5}/_ssgManifest.js +0 -0
@@ -71,10 +71,10 @@ ${(0,n.botGuideLine)()}`};e.s(["buildThreadOpening",0,function(e){if(e.routine){
71
71
 
72
72
  ${e.request.trim()}`}]}let t="user"===e.from?"The user":"Thursday";return[{type:"text",text:`You are ${e.bot}. ${t} hands you this thread${"user"===e.from?" on screen":" during a call"}.`},{type:"text",text:`## ${t} → ${e.bot}: the job
73
73
 
74
- ${e.request.trim()}`}]},"loadBotPrompt",0,k]),a()}catch(e){a(e)}},!1),585099,e=>e.a(async(t,a)=>{try{var r=e.i(68356),o=e.i(847841),n=e.i(687388),i=e.i(159479),s=e.i(386075),l=e.i(851372),d=e.i(316172),h=e.i(353885),u=e.i(944971),c=e.i(786025),w=e.i(640911),p=e.i(388439),b=e.i(265143),m=e.i(378884),f=t([i,s,l,d,b,m]);[i,s,l,d,b,m]=f.then?(await f)():f;let I=n.BOT_RUN.steps;async function y(e,t){var a,f;let y,k,$,W,q,x,R,O,M,A=t.parent??null,S=await (0,b.findJobBot)(e.bot.trim()),N=S?.name??e.bot.trim(),E=e=>t.emit({...e,bot:N,parent:A});if(!S)return void await E({type:"error",message:`No bot named "${e.bot}". Use a name from the list.`,retry:!1});let C=e.messages,_=await ((a=S).provider&&a.model?(0,s.getTextModel)({provider:a.provider,model:a.model}):(0,s.resolveDefaultModel)().then(s.getTextModel)),D=t.threadId?await (0,m.findThread)(t.threadId):null,[B,{own:U,artifacts:P}]=await Promise.all([t.threadId?(0,c.openJobScratch)(t.threadId,D?.label??"job"):null,(0,c.openBotFolders)(N)]),[j,H]=await Promise.all([(0,l.loadBotPrompt)(N,S.systemPrompt,{thread:t.threadId??null,owner:t.owner,caller:t.caller,messageId:A},{scratch:B,own:U,artifacts:P}),(0,i.loadTools)({target:"bot",bot:N,thread:t.threadId??null,session:t.session??(t.threadId?(0,c.botBrowserSession)(t.threadId,N):null),model:_})]),L=Math.min(await (0,s.compactBudget)(_.ref,S.compactAt),t.contextBudget||1/0),Y=!1,F={...H,[h.TOOL_NAMES.send_message]:(0,o.tool)({description:d.sendMessageSpec.description,inputSchema:d.sendMessageSpec.parameters,execute:async(e,a)=>{let r=await t.send({...e,id:a.toolCallId});return"question"===e.kind&&(Y=!0),r}})},J=new Set,K=(f=n.BOT_RUN.silenceMs,k=new AbortController,$=0,W=!1,q=()=>{clearTimeout(y),y=void 0,W||$>0||(y=setTimeout(()=>{k.abort(new DOMException(`The model sent nothing for ${Math.round(f/6e4)} minutes.`,"TimeoutError"))},f))},{signal:k.signal,touch:q,hold:()=>{$+=1,q()},release:()=>{$=Math.max(0,$-1),q()},end:()=>{W=!0,q()}});for(let[e,a]of Object.entries(F)){let r=a.execute;r&&(a.execute=(a,o)=>{let n=(async()=>{t.signal?.throwIfAborted(),await E({type:"tool",id:o.toolCallId,name:e,input:a}),K.hold();try{t.signal?.throwIfAborted();let n=await r(a,o);if(n&&"object"==typeof n&&Symbol.asyncIterator in n){let e;for await(let t of n)e=t;n=e}return await E({type:"tool-result",id:o.toolCallId,name:e,output:n}),n}catch(t){throw await E({type:"tool-result",id:o.toolCallId,name:e,output:(0,s.modelErrorToString)(t),error:!0}),t}finally{K.release()}})();return J.add(n),n.finally(()=>J.delete(n)).catch(()=>{}),n})}let G=Promise.resolve(),z=()=>{},Q=0,V=new r.ToolLoopAgent({model:_.model,instructions:j.text,tools:F,stopWhen:[(0,r.stepCountIs)(I),()=>Y],prepareStep:async({stepNumber:e,steps:a,messages:r})=>{await G,t.signal?.throwIfAborted();let o={},n=a.at(-1)?.usage.inputTokens??0,i=Math.max(n,r.reduce((e,t)=>e+(0,p.estimateTokens)("string"==typeof t.content?t.content:JSON.stringify(t.content))+4,0));Q=i;let s=r,l=t.compactNow?.()??!1;if((i>L||l)&&r.length>2){K.hold();let e=await T(_.model,F,r,{signal:t.signal,budget:L,instructions:j.text}).finally(K.release);w.logger.debug(`compacted ${r.length} messages at ${i} tokens (budget ${L})`);let a=`${e.text}${await g(D?.id??null,r,B)}`;await E({type:"compact",text:a,usage:e.usage,messages:r.length,tokens:i}),s=[r[0],{role:"user",content:a}]}let d=e>0?await t.notes?.()??[]:[];return(d.length&&(s=[...s,...d.map(e=>({role:"user",content:e}))]),s===r)?o:{...o,messages:s}}}),X=(x=[],R=[],O=!1,{push(e){let t=R.shift();t?t(e):x.push(e)},take(){let e=x.shift();return e?Promise.resolve(e):O?Promise.resolve(null):new Promise(e=>R.push(e))},end(){for(let e of(O=!0,R.splice(0)))e(null)}}),Z=t.signal?AbortSignal.any([t.signal,K.signal]):K.signal;K.touch();let ee=new AbortController,et=AbortSignal.any([Z,ee.signal]);try{M=await V.stream({messages:C,abortSignal:et,onStepEnd:e=>{G=new Promise(e=>{z=e}),X.push({messages:e.response.messages,usage:v(e.usage)})}})}catch(e){throw K.end(),ee.abort(),await Promise.allSettled([...J]),e}let ea="",er="",eo=null,en=e=>{w.logger.error(`${N}: the model run broke`,e);let t=(0,s.modelErrorToString)(e),a=!(0,s.isProviderRefusal)(e);if(!(0,s.isContextOverflow)(e))return{type:"error",message:t,retry:a};let r=Math.floor(Math.min(L,Q||L)*n.BOT_RUN.overflowShrink);return{type:"error",message:t,budget:Math.max(u.COMPACT_AT_MIN,r),retry:a}};Z.addEventListener("abort",()=>{X.end(),z()},{once:!0});try{for await(let e of M.stream)switch(K.touch(),e.type){case"start-step":er="",ea="";break;case"text-delta":ea+=e.text;break;case"text-end":{let e=ea.trim();if(ea="",!e)break;er=[er,e].filter(Boolean).join("\n\n"),await E({type:"text",text:e});break}case"tool-call":await E({type:"tool",id:e.toolCallId,name:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:e.providerMetadata});break;case"tool-result":await E({type:"tool-result",id:e.toolCallId,name:e.toolName,output:e.output});break;case"tool-error":await E({type:"tool-result",id:e.toolCallId,name:e.toolName,output:(0,s.modelErrorToString)(e.error),error:!0});break;case"finish-step":{eo=e.finishReason;let t=await X.take();t&&await E({type:"step",...t,budget:L}),z();break}case"abort":if(t.signal?.aborted)return;await E(en(e.reason??"The model stopped sending."));return;case"error":await E(en(e.error));return}}finally{ee.abort(),X.end(),K.end(),z(),await Promise.allSettled([...J])}try{await M.finalStep}catch(e){if(t.signal?.aborted)return;await E(en(e));return}"content-filter"===eo?await E({type:"error",message:"The provider's content filter stopped the response.",retry:!1}):await E({type:"turn-end",text:er,stopped:!Y&&("length"===eo||"error"===eo||"tool-calls"===eo)})}async function g(e,t,a){try{let r=e?await (0,m.listWrittenPaths)(e):(0,m.writtenPathsIn)(t.map(e=>e.content)),o=await (0,c.filesOnDisk)(r,a);if(!o.length)return"";let i=o.slice(-n.BOT_RUN.compactFiles),s=o.length-i.length,l=i.map(e=>`- ${e}`);return s&&l.unshift(`- …and ${s} older ones`),`
74
+ ${e.request.trim()}`}]},"loadBotPrompt",0,k]),a()}catch(e){a(e)}},!1),585099,e=>e.a(async(t,a)=>{try{var r=e.i(68356),o=e.i(847841),n=e.i(687388),i=e.i(159479),s=e.i(386075),l=e.i(851372),d=e.i(316172),h=e.i(353885),u=e.i(944971),c=e.i(527608),w=e.i(786025),p=e.i(640911),b=e.i(388439),m=e.i(265143),f=e.i(378884),y=t([i,s,l,d,m,f]);[i,s,l,d,m,f]=y.then?(await y)():y;let v=n.BOT_RUN.steps;async function g(e,t){var a,y;let g,I,W,q,x,R,O,M,A,S=t.parent??null,N=await (0,m.findJobBot)(e.bot.trim()),E=N?.name??e.bot.trim(),C=e=>t.emit({...e,bot:E,parent:S});if(!N)return void await C({type:"error",message:`No bot named "${e.bot}". Use a name from the list.`,retry:!1});let _=e.messages,D=await ((a=N).provider&&a.model?(0,s.getTextModel)({provider:a.provider,model:a.model}):(0,s.resolveDefaultModel)().then(s.getTextModel)),B=t.threadId?await (0,f.findThread)(t.threadId):null,[U,{own:P,artifacts:j}]=await Promise.all([t.threadId?(0,w.openJobScratch)(t.threadId,B?.label??"job"):null,(0,w.openBotFolders)(E)]),H=t.session??(t.threadId?(0,w.botBrowserSession)(t.threadId,E):null),[L,Y]=await Promise.all([(0,l.loadBotPrompt)(E,N.systemPrompt,{thread:t.threadId??null,owner:t.owner,caller:t.caller,messageId:S},{scratch:U,own:P,artifacts:j}),(0,i.loadTools)({target:"bot",bot:E,thread:t.threadId??null,session:H,model:D})]),F=Math.min(await (0,s.compactBudget)(D.ref,N.compactAt),t.contextBudget||1/0),J=!1,K={...Y,[h.TOOL_NAMES.send_message]:(0,o.tool)({description:d.sendMessageSpec.description,inputSchema:d.sendMessageSpec.parameters,execute:async(e,a)=>{let r=await t.send({...e,id:a.toolCallId});return"question"===e.kind&&(J=!0),r}})},G=new Set,z=(y=n.BOT_RUN.silenceMs,I=new AbortController,W=0,q=!1,x=()=>{clearTimeout(g),g=void 0,q||W>0||(g=setTimeout(()=>{I.abort(new DOMException(`The model sent nothing for ${Math.round(y/6e4)} minutes.`,"TimeoutError"))},y))},{signal:I.signal,touch:x,hold:()=>{W+=1,x()},release:()=>{W=Math.max(0,W-1),x()},end:()=>{q=!0,x()}});for(let[e,a]of Object.entries(K)){let r=a.execute;r&&(a.execute=(a,o)=>{let n=(async()=>{t.signal?.throwIfAborted(),await C({type:"tool",id:o.toolCallId,name:e,input:a}),z.hold();try{t.signal?.throwIfAborted();let n=await r(a,o);if(n&&"object"==typeof n&&Symbol.asyncIterator in n){let e;for await(let t of n)e=t;n=e}return await C({type:"tool-result",id:o.toolCallId,name:e,output:n}),n}catch(t){throw await C({type:"tool-result",id:o.toolCallId,name:e,output:(0,s.modelErrorToString)(t),error:!0}),t}finally{z.release()}})();return G.add(n),n.finally(()=>G.delete(n)).catch(()=>{}),n})}let Q=Promise.resolve(),V=()=>{},X=0,Z=new r.ToolLoopAgent({model:D.model,instructions:L.text,tools:K,stopWhen:[(0,r.stepCountIs)(v),()=>J],prepareStep:async({stepNumber:e,steps:a,messages:r})=>{await Q,t.signal?.throwIfAborted();let o={},n=a.at(-1)?.usage.inputTokens??0,i=Math.max(n,r.reduce((e,t)=>e+(0,b.estimateTokens)("string"==typeof t.content?t.content:JSON.stringify(t.content))+4,0));X=i;let s=r,l=t.compactNow?.()??!1;if((i>F||l)&&r.length>2){z.hold();let e=await k(D.model,K,r,{signal:t.signal,budget:F,instructions:L.text}).finally(z.release);p.logger.debug(`compacted ${r.length} messages at ${i} tokens (budget ${F})`);let a=`${e.text}${await T(B?.id??null,r,U)}`;await C({type:"compact",text:a,usage:e.usage,messages:r.length,tokens:i}),s=[r[0],{role:"user",content:a}]}let d=e>0?await t.notes?.()??[]:[];return(d.length&&(s=[...s,...d.map(e=>({role:"user",content:e}))]),s===r)?o:{...o,messages:s}}}),ee=(R=[],O=[],M=!1,{push(e){let t=O.shift();t?t(e):R.push(e)},take(){let e=R.shift();return e?Promise.resolve(e):M?Promise.resolve(null):new Promise(e=>O.push(e))},end(){for(let e of(M=!0,O.splice(0)))e(null)}}),et=t.signal?AbortSignal.any([t.signal,z.signal]):z.signal;z.touch();let ea=new AbortController,er=AbortSignal.any([et,ea.signal]);try{A=await Z.stream({messages:_,abortSignal:er,onStepEnd:e=>{Q=new Promise(e=>{V=e}),ee.push({messages:e.response.messages,usage:$(e.usage)})}})}catch(e){throw z.end(),ea.abort(),await Promise.allSettled([...G]),e}let eo="",en="",ei=null,es=e=>{p.logger.error(`${E}: the model run broke`,e);let t=(0,s.modelErrorToString)(e),a=!(0,s.isProviderRefusal)(e);if(!(0,s.isContextOverflow)(e))return{type:"error",message:t,retry:a};let r=Math.floor(Math.min(F,X||F)*n.BOT_RUN.overflowShrink);return{type:"error",message:t,budget:Math.max(u.COMPACT_AT_MIN,r),retry:a}};et.addEventListener("abort",()=>{ee.end(),V()},{once:!0});try{for await(let e of A.stream)switch(z.touch(),e.type){case"start-step":en="",eo="";break;case"text-delta":eo+=e.text;break;case"text-end":{let e=eo.trim();if(eo="",!e)break;en=[en,e].filter(Boolean).join("\n\n"),await C({type:"text",text:e});break}case"tool-call":await C({type:"tool",id:e.toolCallId,name:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:e.providerMetadata});break;case"tool-result":await C({type:"tool-result",id:e.toolCallId,name:e.toolName,output:e.output});break;case"tool-error":await C({type:"tool-result",id:e.toolCallId,name:e.toolName,output:(0,s.modelErrorToString)(e.error),error:!0});break;case"finish-step":{ei=e.finishReason;let t=await ee.take();t&&await C({type:"step",...t,budget:F}),V();break}case"abort":if(t.signal?.aborted)return;await C(es(e.reason??"The model stopped sending."));return;case"error":await C(es(e.error));return}}finally{ea.abort(),ee.end(),z.end(),V(),await Promise.allSettled([...G]),H&&(0,c.renewSignIns)(H).catch(e=>p.logger.warn(`${E}: kept sign-ins were not renewed`,e))}try{await A.finalStep}catch(e){if(t.signal?.aborted)return;await C(es(e));return}"content-filter"===ei?await C({type:"error",message:"The provider's content filter stopped the response.",retry:!1}):await C({type:"turn-end",text:en,stopped:!J&&("length"===ei||"error"===ei||"tool-calls"===ei)})}async function T(e,t,a){try{let r=e?await (0,f.listWrittenPaths)(e):(0,f.writtenPathsIn)(t.map(e=>e.content)),o=await (0,w.filesOnDisk)(r,a);if(!o.length)return"";let i=o.slice(-n.BOT_RUN.compactFiles),s=o.length-i.length,l=i.map(e=>`- ${e}`);return s&&l.unshift(`- …and ${s} older ones`),`
75
75
 
76
76
  Files this job has on disk now — open one rather than fetching again what is in it:
77
- ${l.join("\n")}`}catch(e){return w.logger.warn("files under the summary could not be listed",e),""}}async function T(e,t,a,o){let n;try{return await k(e,t,a,o)}catch(e){if(o.signal?.aborted)throw e;n=e}if((0,s.isContextOverflow)(n)){let i=(0,r.pruneMessages)({messages:a,toolCalls:"before-last-4-messages",emptyMessages:"remove"});try{return await k(e,t,i,o)}catch(e){if(o.signal?.aborted)throw e;n=e}}throw Error(`Could not compact the context (${(0,s.modelErrorToString)(n)}).`,{cause:n})}async function k(e,t,a,o){let i,{text:s,usage:l}=await (0,r.generateText)({model:e,instructions:o.instructions,tools:t,toolChoice:"none",messages:[...a,{role:"user",content:(i=(e=>{let{min:t,max:a,perTokens:r}=n.BOT_RUN.summaryWords;return Math.min(a,Math.max(t,Math.round(e/r)))})(o.budget),`Compact your context. The first message above — who handed you the job, and the job — stays exactly as it is. Everything after it is replaced by what you write now, and you carry on from that first message and this alone; nothing else above can be read again. Write it for a fresh copy of you that has your tools, your instructions and that first message, but has seen none of the rest.
77
+ ${l.join("\n")}`}catch(e){return p.logger.warn("files under the summary could not be listed",e),""}}async function k(e,t,a,o){let n;try{return await I(e,t,a,o)}catch(e){if(o.signal?.aborted)throw e;n=e}if((0,s.isContextOverflow)(n)){let i=(0,r.pruneMessages)({messages:a,toolCalls:"before-last-4-messages",emptyMessages:"remove"});try{return await I(e,t,i,o)}catch(e){if(o.signal?.aborted)throw e;n=e}}throw Error(`Could not compact the context (${(0,s.modelErrorToString)(n)}).`,{cause:n})}async function I(e,t,a,o){let i,{text:s,usage:l}=await (0,r.generateText)({model:e,instructions:o.instructions,tools:t,toolChoice:"none",messages:[...a,{role:"user",content:(i=(e=>{let{min:t,max:a,perTokens:r}=n.BOT_RUN.summaryWords;return Math.min(a,Math.max(t,Math.round(e/r)))})(o.budget),`Compact your context. The first message above — who handed you the job, and the job — stays exactly as it is. Everything after it is replaced by what you write now, and you carry on from that first message and this alone; nothing else above can be read again. Write it for a fresh copy of you that has your tools, your instructions and that first message, but has seen none of the rest.
78
78
 
79
79
  Cover all of it, and prefer a fact over a description of a fact:
80
80
 
@@ -87,7 +87,7 @@ Cover all of it, and prefer a fact over a description of a fact:
87
87
 
88
88
  Plain text, under ${i} words. No preamble, no headings about the summary itself, no account of how you have been going.`)}],abortSignal:o.signal,timeout:n.BOT_RUN.silenceMs}),d=s.trim();if(!d)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.
89
89
 
90
- ${d}`,usage:v(l)}}let v=e=>({input:e.inputTokens??0,output:e.outputTokens??0});e.s(["resumeTranscript",0,function(e,t=new Map){let a=new Map,r=new Set;for(let t of e)if(("tool"===t.role||"assistant"===t.role)&&Array.isArray(t.content))for(let e of t.content)"tool-result"===e.type&&(a.has(e.toolCallId)||a.set(e.toolCallId,e),"assistant"===t.role&&r.add(e.toolCallId));let o=[],n=new Set;for(let i of e){if("tool"===i.role){let e=i.content.filter(e=>"tool-result"!==e.type);e.length&&o.push({...i,content:e});continue}if("assistant"!==i.role||"string"==typeof i.content){o.push(i);continue}let e=[],s=[];for(let o of i.content){if("tool-call"!==o.type){s.push(o);continue}if(n.has(o.toolCallId))continue;let i=o.input;if("string"==typeof i)try{i=JSON.parse(i)}catch{i=void 0}if(!o.toolCallId||void 0===i){s.push({type:"text",text:"A tool argument stream was interrupted before a complete call was recorded. Inspect the saved work before continuing."});continue}let l=o.toolName===h.TOOL_NAMES.send_message?t.get(o.toolCallId):void 0,d=a.get(o.toolCallId)??(l?{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:{type:"json",value:l}}:void 0);if(o.providerExecuted&&(!d||!r.has(o.toolCallId))){s.push({type:"text",text:d?`The provider operation ${o.toolName} returned this data before its native continuation was interrupted: ${JSON.stringify(d.output)}`:`The provider operation ${o.toolName} was interrupted without a recorded result. Its remote execution state is unknown.`});continue}n.add(o.toolCallId),s.push({...o,input:i}),r.has(o.toolCallId)||e.push(d??{type:"tool-result",toolCallId:o.toolCallId,toolName:o.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."}})}s.length&&o.push({...i,content:s}),e.length&&o.push({role:"tool",content:e})}return o},"runBot",0,y]),a()}catch(e){a(e)}},!1),39803,e=>e.a(async(t,a)=>{try{var r=e.i(136340),o=e.i(380690),n=e.i(687388),i=e.i(386075),s=e.i(851372),l=e.i(22676),d=e.i(629668),h=e.i(786025),u=e.i(167004),c=e.i(640911),w=e.i(53748),p=e.i(268486),b=e.i(41444),m=e.i(265143),f=e.i(585099),y=e.i(944971),g=e.i(742712),T=e.i(889034),k=e.i(378884),I=t([i,s,l,m,f,g,k]);[i,s,l,m,f,g,k]=I.then?(await I)():I;let D=globalThis.__roomRuns??=new Map,B=globalThis.__roomThreadLock??=(0,p.createKeyedLock)(),U=globalThis.__roomPausing??={current:Promise.resolve()},P=globalThis.__roomCompactAsked??=new Set,j=(e,t)=>`${e}
90
+ ${d}`,usage:$(l)}}let $=e=>({input:e.inputTokens??0,output:e.outputTokens??0});e.s(["resumeTranscript",0,function(e,t=new Map){let a=new Map,r=new Set;for(let t of e)if(("tool"===t.role||"assistant"===t.role)&&Array.isArray(t.content))for(let e of t.content)"tool-result"===e.type&&(a.has(e.toolCallId)||a.set(e.toolCallId,e),"assistant"===t.role&&r.add(e.toolCallId));let o=[],n=new Set;for(let i of e){if("tool"===i.role){let e=i.content.filter(e=>"tool-result"!==e.type);e.length&&o.push({...i,content:e});continue}if("assistant"!==i.role||"string"==typeof i.content){o.push(i);continue}let e=[],s=[];for(let o of i.content){if("tool-call"!==o.type){s.push(o);continue}if(n.has(o.toolCallId))continue;let i=o.input;if("string"==typeof i)try{i=JSON.parse(i)}catch{i=void 0}if(!o.toolCallId||void 0===i){s.push({type:"text",text:"A tool argument stream was interrupted before a complete call was recorded. Inspect the saved work before continuing."});continue}let l=o.toolName===h.TOOL_NAMES.send_message?t.get(o.toolCallId):void 0,d=a.get(o.toolCallId)??(l?{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:{type:"json",value:l}}:void 0);if(o.providerExecuted&&(!d||!r.has(o.toolCallId))){s.push({type:"text",text:d?`The provider operation ${o.toolName} returned this data before its native continuation was interrupted: ${JSON.stringify(d.output)}`:`The provider operation ${o.toolName} was interrupted without a recorded result. Its remote execution state is unknown.`});continue}n.add(o.toolCallId),s.push({...o,input:i}),r.has(o.toolCallId)||e.push(d??{type:"tool-result",toolCallId:o.toolCallId,toolName:o.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."}})}s.length&&o.push({...i,content:s}),e.length&&o.push({role:"tool",content:e})}return o},"runBot",0,g]),a()}catch(e){a(e)}},!1),39803,e=>e.a(async(t,a)=>{try{var r=e.i(136340),o=e.i(380690),n=e.i(687388),i=e.i(386075),s=e.i(851372),l=e.i(22676),d=e.i(629668),h=e.i(786025),u=e.i(167004),c=e.i(640911),w=e.i(53748),p=e.i(268486),b=e.i(41444),m=e.i(265143),f=e.i(585099),y=e.i(944971),g=e.i(742712),T=e.i(889034),k=e.i(378884),I=t([i,s,l,m,f,g,k]);[i,s,l,m,f,g,k]=I.then?(await I)():I;let D=globalThis.__roomRuns??=new Map,B=globalThis.__roomThreadLock??=(0,p.createKeyedLock)(),U=globalThis.__roomPausing??={current:Promise.resolve()},P=globalThis.__roomCompactAsked??=new Set,j=(e,t)=>`${e}
91
91
  ${t}`;async function v(e){let t=await (0,m.findJobBot)(e.bot);(!t||t.disabled)&&(0,w.publicError)("Choose an enabled bot.");let{from:a,routine:r,...o}={...e,bot:t.name},n=(0,s.buildThreadOpening)({bot:o.bot,request:o.request,from:a,routine:r}),i=await (0,k.insertThread)({...o,routineId:r?.id??null,opening:n});return await W(i.id),i.id}async function $(e,t,a="user",r,o){let n=null;return await B(e,async()=>{let i=await (0,k.findThread)(e);if(i||(0,w.publicError)("No such thread."),r){let t=(await (0,g.listRoomWork)(e)).find(e=>e.bot.toLowerCase()===r.trim().toLowerCase());t&&t.bot!==T.ROOM_THURSDAY||(0,w.publicError)("Choose a participant in this thread."),r=t.bot}t.trim()===y.THREAD_CONTINUE&&(0,y.isAppStop)(i.pending)?(await (0,g.resumeRoom)(e),(await (0,g.listRoomWork)(e)).some(e=>"queued"===e.state)||(n=await (0,g.tellRoom)(e,"Continue from the saved conversation.","user"===a?"The user":T.ROOM_THURSDAY,r,void 0,!1))):n=await (0,g.tellRoom)(e,t,"user"===a?"The user":T.ROOM_THURSDAY,r,o)}),await W(e),n}async function W(e){await B(e,async()=>{if(!o.presence.watching&&!await (0,m.readKeepWorkingOn)()){let t=await (0,k.findThread)(e);t?.status!=="running"||[...D.values()].some(t=>t.threadId===e)||await (0,g.pauseRoom)(e,"The app is not open. Work resumes when it returns.",!0);return}for(let t=0;t<2;t++){let t;for(;t=await (0,g.claimRoomWork)(e);)!function(e){let t,a=new AbortController,r=new Promise(e=>{t=e});D.set(e.id,{threadId:e.threadId,stop:a,done:r}),q(e,a.signal).catch(t=>c.logger.error(`thread ${e.threadId}: participant`,t)).finally(()=>{D.delete(e.id),t(),W(e.threadId).catch(t=>c.logger.error(`thread ${e.threadId}: scheduling`,t))})}(t);await (0,g.settleRoom)(e)}})}async function q(e,t){let a=await x(e,t);if(a?.failure?.retry&&!t.aborted&&(await (0,g.noteRoomBreak)(e,a.failure.message),await (0,r.setTimeout)(n.BOT_RUN.retryMs,void 0,{signal:t}).catch(()=>{}),t.aborted||(a=await x(e,t))),!a||t.aborted)return;let i=a.failure?.message,s=a.ending;if(i||!s||s.stopped){let t=i??"The turn was interrupted. Continue from the saved conversation.";B(e.threadId,async()=>{let a=(await (0,g.listRoomWork)(e.threadId)).find(t=>t.id===e.id);if(a?.state!=="running"||a.generation!==e.generation)return;let r=R(e.threadId);await (0,g.pauseRoom)(e.threadId,t),await r}).catch(t=>c.logger.error(`thread ${e.threadId}: pausing`,t));return}await (0,g.finishRoomWork)(e,s.text);let w=await (0,k.findThread)(e.threadId);if(w?.status==="done"){o.presence.watching||await (0,l.isAnyCallLive)()||(0,u.desktopNotify)(w.label,w.outcome??"");let e=await (0,h.filesOnDisk)((0,d.pathsIn)(w.outcome??""),null),t=e.findIndex(d.opensOnFinish);o.appEvents.emit({type:"finished",threadId:w.id,label:w.label,bot:w.bot,words:(0,b.plainText)(w.outcome??"").slice(0,n.FINISHED_NOTICE.words),paths:t>0?[e[t],...e.filter((e,a)=>a!==t)]:e})}}async function x(e,t){let a=new H(e,t),r=null,o=null;try{let n=await (0,k.findThread)(e.threadId);if(!n)return null;(await (0,g.listParticipantTranscript)(e.threadId,e.bot)).length||await (0,g.appendRoomMessage)(e.threadId,{bot:e.bot,parent:e.id,role:"user",content:`Request: ${n.request}
92
92
  Coordinator: ${n.bot}. Continue as ${e.bot} in this thread.`,hidden:!0}),await (0,g.consumeRoomInbox)(e);let i=await (0,g.listParticipantTranscript)(e.threadId,e.bot);await (0,f.runBot)({bot:e.bot,messages:(0,f.resumeTranscript)(i,await (0,g.listRoomReceipts)(e.threadId,e.bot,i))},{signal:t,threadId:e.threadId,parent:e.id,caller:e.caller,owner:n.bot,contextBudget:await (0,g.roomContextBudget)(e.threadId,e.bot),compactNow:()=>P.delete(j(e.threadId,e.bot)),session:(0,h.botBrowserSession)(e.threadId,e.bot),notes:()=>(0,g.consumeRoomInbox)(e),send:async a=>{t.throwIfAborted();let r=a.to.trim();if(r.toLowerCase()===T.ROOM_THURSDAY.toLowerCase())r=T.ROOM_THURSDAY;else{let e=await (0,m.findJobBot)(r);(!e||e.disabled)&&(0,w.publicError)(`No enabled bot named "${r}".`),r=e.name}let o=await (0,g.sendRoomMessage)(e,{...a,to:r});return W(e.threadId).catch(e=>c.logger.error("room message scheduling",e)),o},emit:async i=>{(!t.aborted||"tool-result"===i.type)&&(await a.on(i),"step"===i.type&&await (0,k.addThreadUsage)(e.threadId,i.usage,e.bot===n.bot?{tokens:i.usage.input,budget:i.budget}:null),"compact"===i.type&&await (0,k.addThreadUsage)(e.threadId,i.usage),"turn-end"===i.type&&(r=i),"error"===i.type&&(o={message:i.message,retry:i.retry},i.budget&&await (0,g.lowerRoomContextBudget)(e,i.budget)))}})}catch(a){t.aborted||(c.logger.error(`thread ${e.threadId}: ${e.bot} broke`,a),o={message:(0,i.modelErrorToString)(a),retry:!(0,w.isPublicError)(a)&&!(0,i.isProviderRefusal)(a)})}return{ending:r,failure:o}}class H{work;signal;lane;assistant;tool;parts;calls;results;constructor(e,t){this.work=e,this.signal=t,this.lane=(0,b.PromiseChain)(),this.assistant=null,this.tool=null,this.parts={assistant:[],tool:[]},this.calls=new Set,this.results=new Set}async write(e,t,a=!1){let r={bot:this.work.bot,parent:this.work.id,role:t.role,content:t.content,compact:a,note:a};return null===e?(0,g.appendRoomMessage)(this.work.threadId,r):(await (0,k.upsertMessage)(this.work.threadId,e,r),e)}on(e){return this.lane(async()=>{if(!this.signal.aborted||"tool-result"===e.type)if("text"===e.type)this.parts.assistant.push({type:"text",text:e.text}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant});else if("tool"===e.type){if(this.calls.has(e.id)){let t=this.parts.assistant.find(t=>"tool-call"===t.type&&t.toolCallId===e.id);t&&"tool-call"===t.type&&e.providerOptions&&(t.providerOptions=e.providerOptions,this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant}));return}this.calls.add(e.id),this.parts.assistant.push({type:"tool-call",toolCallId:e.id,toolName:e.name,input:e.input,...e.providerExecuted?{providerExecuted:!0}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{}}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant})}else if("tool-result"===e.type){if(this.results.has(e.id))return;this.results.add(e.id),this.parts.tool.push({type:"tool-result",toolCallId:e.id,toolName:e.name,output:e.error?{type:"error-text",value:String(e.output)}:"string"==typeof e.output?{type:"text",value:e.output}:{type:"json",value:e.output}}),this.tool=await this.write(this.tool,{role:"tool",content:this.parts.tool})}else if("step"===e.type){let t=[this.assistant,this.tool];for(let[a,r]of e.messages.entries())await this.write(t[a]??null,r);let a=t.slice(e.messages.length).filter(e=>null!==e);a.length&&await (0,k.deleteMessages)(this.work.threadId,a),this.assistant=this.tool=null,this.parts={assistant:[],tool:[]}}else"compact"===e.type&&await this.write(null,{role:"user",content:e.text},!0)})}}async function R(e){let t=[...D.values()].filter(t=>t.threadId===e);for(let e of t)e.stop.abort();await Promise.all(t.map(e=>e.done))}async function O(e){await B(e,async()=>{let t=await (0,k.findThread)(e);t||(0,w.publicError)("No such thread."),t.endedAt&&(0,w.publicError)("That thread has already ended."),await (0,g.cancelRoom)(e),await (0,k.updateThread)(e,{status:"cancelled",outcome:null,pending:null,seen:!0,endedAt:new Date}),await R(e),await (0,h.closeJobShell)(e)})}async function M(e){return B(e,()=>A(e))}async function A(e){let t=await (0,k.findThread)(e);await (0,g.cancelRoom)(e),await R(e),await (0,h.removeJobBrowsers)(e);let a=await (0,k.deleteThread)(e);return a&&t&&await (0,h.removeJobScratch)(e,t.label),a}async function S(){let e=0;for(let t of(await (0,k.listThreadFolders)()))("done"===t.status||"cancelled"===t.status)&&await B(t.id,async()=>{let a=await (0,k.findThread)(t.id);(a?.status==="done"||a?.status==="cancelled")&&await A(t.id)&&(e+=1)});return e}async function N(){let e=Date.now()-n.WORKSPACE_KEEP.forMs,t=t=>("done"===t.status||"cancelled"===t.status)&&(t.endedAt??t.updatedAt).getTime()<e,a=new Set(await (0,h.listScratchFolders)()),r=[];for(let e of(await (0,k.listThreadFolders)())){let o=(0,h.jobScratch)(e.id,e.label);a.delete(o)&&t(e)&&await B(e.id,async()=>{let a=await (0,k.findThread)(e.id);a&&t(a)&&(await (0,h.closeHiddenBrowser)(e.id),await (0,h.removeJobScratch)(e.id,e.label),r.push(o))})}return r.push(...await (0,h.removeUnchangedFolders)([...a])),await (0,h.pruneJobFiles)(),r.length&&c.logger.info(`cleared ${r.length} old job folder(s): ${r.join(", ")}`),r}async function E(){for(let e of(await (0,k.listRunningThreadIds)()))await B(e,async()=>{[...D.values()].some(t=>t.threadId===e)||(await (0,k.findThread)(e))?.status==="running"&&await (0,g.pauseRoom)(e,"The server restarted. Resume from the saved conversation.")})}async function C(e,t=!1){let a=(async()=>{let a=await (0,k.listRunningThreadIds)();await Promise.all(a.map(a=>B(a,async()=>{(await (0,k.findThread)(a))?.status==="running"&&(await R(a),await (0,g.pauseRoom)(a,e,t))})))})();U.current=a,await a}async function _(){if(await U.current,o.presence.watching)for(let e of(await (0,k.listAutoStoppedThreads)()))await B(e,async()=>{let t=await (0,k.findThread)(e);t?.status==="waiting"&&t.pending?.auto&&await (0,g.resumeRoom)(e,!1)}),await W(e)}e.s(["answerThread",0,$,"askCompact",0,function(e,t){P.add(j(e,t))},"cancelThread",0,O,"pauseThreads",0,C,"removeFinishedThreads",0,S,"removeThread",0,M,"resumeStoppedThreads",0,_,"startThread",0,v,"sweepJobFiles",0,N,"sweepThreads",0,E]),a()}catch(e){a(e)}},!1),742712,e=>e.a(async(t,a)=>{try{var r=e.i(666680),o=e.i(875225),n=e.i(260338),i=e.i(518899),s=e.i(380690),l=e.i(687388),d=e.i(528790),h=e.i(613240),u=e.i(353885),c=e.i(53748),w=e.i(944971),p=e.i(889034),b=t([d]);[d]=b.then?(await b)():b;let B=()=>s.appEvents.emit({type:"threads"}),U=e=>"done"===e||"cancelled"===e,P=(e,t,a)=>`message:${(0,r.createHash)("sha256").update(JSON.stringify([e,t,a])).digest("hex")}`;async function m(e,t,a){let[r]=await e.select({id:h.threadWorkTable.id}).from(h.threadWorkTable).where((0,o.and)((0,o.eq)(h.threadWorkTable.threadId,t),(0,o.eq)(h.threadWorkTable.state,"external"),(0,o.eq)(h.threadWorkTable.caller,a))).limit(1);return!!r}async function f(e,t,a){let r=a.flatMap(e=>"assistant"===e.role&&Array.isArray(e.content)?e.content.flatMap(e=>"tool-call"===e.type&&e.toolName===u.TOOL_NAMES.send_message?[e.toolCallId]:[]):[]),n=r.map(a=>P(e,t,a)),i=new Map;if(!n.length)return i;let[s,l]=await Promise.all([d.database.select({key:h.threadWorkTable.id,to:h.threadWorkTable.bot}).from(h.threadWorkTable).where((0,o.and)((0,o.eq)(h.threadWorkTable.threadId,e),(0,o.inArray)(h.threadWorkTable.id,n))),d.database.select({key:h.threadDeliveryTable.key,to:h.threadWorkTable.bot}).from(h.threadDeliveryTable).innerJoin(h.threadWorkTable,(0,o.eq)(h.threadWorkTable.id,h.threadDeliveryTable.workId)).where((0,o.and)((0,o.eq)(h.threadDeliveryTable.threadId,e),(0,o.inArray)(h.threadDeliveryTable.key,n)))]),c=new Map([...s,...l].map(e=>[e.key,e.to]));for(let[e,t]of r.entries()){let a=c.get(n[e]);a&&i.set(t,{messageId:n[e],to:a})}return i}async function y(e,t,a){let[r]=await e.select({seq:(0,n.max)(h.threadMessageTable.seq)}).from(h.threadMessageTable).where((0,o.eq)(h.threadMessageTable.threadId,t)),i=(r?.seq??-1)+1;return await e.insert(h.threadMessageTable).values({threadId:t,seq:i,...a}),i}let j=(e,t)=>({bot:e.bot,parent:e.id,role:"user",content:`${t} ${p.RESUME_CHECK}`,note:!0});async function g(e,t){await T(e.threadId,j(e,t))}async function T(e,t){let a=await d.database.transaction(a=>y(a,e,t));return B(),a}async function k(e){return d.database.select().from(h.threadWorkTable).where((0,o.eq)(h.threadWorkTable.threadId,e)).orderBy(h.threadWorkTable.createdAt,h.threadWorkTable.id)}async function I(e,t){let[a]=await d.database.select({budget:i.sql`min(nullif(${h.threadWorkTable.contextBudget}, 0))`}).from(h.threadWorkTable).where((0,o.and)((0,o.eq)(h.threadWorkTable.threadId,e),(0,o.eq)(h.threadWorkTable.bot,t)));return a?.budget??void 0}async function v(e,t){await d.database.transaction(async a=>{await $(a,e),await a.update(h.threadWorkTable).set({contextBudget:t}).where((0,o.eq)(h.threadWorkTable.id,e.id))}),B()}async function $(e,t){let[a]=await e.select().from(h.threadWorkTable).where((0,o.and)((0,o.eq)(h.threadWorkTable.id,t.id),(0,o.eq)(h.threadWorkTable.generation,t.generation),(0,o.eq)(h.threadWorkTable.state,"running")));return a||(0,c.publicError)("This turn is no longer running."),a}async function W(e,t){await e.insert(h.threadDeliveryTable).values(t).onConflictDoNothing();let[a]=await e.select({bot:h.threadWorkTable.bot}).from(h.threadWorkTable).where((0,o.eq)(h.threadWorkTable.id,t.workId));a&&await m(e,t.threadId,a.bot)||await e.update(h.threadWorkTable).set({state:"queued"}).where((0,o.and)((0,o.eq)(h.threadWorkTable.id,t.workId),(0,o.inArray)(h.threadWorkTable.state,["waiting","done"])))}async function q(e,t){let a={...p.RoomMessageSchema.parse(t),id:t.id};"question"===a.kind&&a.to!==p.ROOM_THURSDAY&&(0,c.publicError)("Address user questions to Thursday; use a message to contact another bot."),a.options?.length&&"question"!==a.kind&&(0,c.publicError)("Offer answer choices only with a user question.");let r=await d.database.transaction(async t=>{await $(t,e);let r=P(e.threadId,e.bot,a.id),[n]=await t.select().from(h.threadWorkTable).where((0,o.eq)(h.threadWorkTable.id,r));if(n)return{messageId:r,to:n.bot};let[i]=await t.select({to:h.threadWorkTable.bot}).from(h.threadDeliveryTable).innerJoin(h.threadWorkTable,(0,o.eq)(h.threadWorkTable.id,h.threadDeliveryTable.workId)).where((0,o.eq)(h.threadDeliveryTable.key,r));if(i)return{messageId:r,to:i.to};if(a.to===e.bot&&(0,c.publicError)("Continue your own work directly; choose another recipient."),a.replyTo){let[n]=await t.select().from(h.threadWorkTable).where((0,o.and)((0,o.eq)(h.threadWorkTable.id,a.replyTo),(0,o.eq)(h.threadWorkTable.threadId,e.threadId)));if((!n||n.bot!==e.bot||n.caller!==a.to||U(n.state))&&(0,c.publicError)("Reply to an open message addressed to you from that recipient."),n.parentId)return await W(t,{key:r,threadId:e.threadId,workId:n.parentId,speaker:e.bot,text:a.text}),{messageId:r,to:a.to}}let s=await t.select().from(h.threadWorkTable).where((0,o.eq)(h.threadWorkTable.threadId,e.threadId)),d=new Set(s.map(e=>e.bot).filter(e=>e!==p.ROOM_THURSDAY));a.to!==p.ROOM_THURSDAY&&!d.has(a.to)&&d.size>=l.BOT_RUN.participants&&(0,c.publicError)("This thread has reached its participant limit."),s.filter(e=>!U(e.state)).length>=l.BOT_RUN.queuedMessages&&(0,c.publicError)("This thread has reached its pending message limit.");let u=a.to!==p.ROOM_THURSDAY&&await m(t,e.threadId,a.to);return await t.insert(h.threadWorkTable).values({id:r,threadId:e.threadId,bot:a.to,caller:e.bot,parentId:e.id,state:a.to===p.ROOM_THURSDAY?"question"===a.kind?"external":"done":u?"waiting":"queued",result:a.to===p.ROOM_THURSDAY?a.text:null,options:[...new Set(a.options??[])]}),a.to===p.ROOM_THURSDAY?await t.insert(h.threadRelayTable).values({key:r,threadId:e.threadId,bot:e.bot,text:a.text,kind:a.kind,messageId:"question"===a.kind?r:null}):await W(t,{key:r,threadId:e.threadId,workId:r,speaker:e.bot,text:a.text}),await t.update(h.threadTable).set({wrapped:!1,updatedAt:new Date}).where((0,o.eq)(h.threadTable.id,e.threadId)),{messageId:r,to:a.to,...u?{note:`${a.to} is waiting for the user's answer and reads this after it.`}:{}}});return B(),r}async function x(e){let t=!1,a=await d.database.transaction(async a=>{let[r]=await a.select().from(h.threadTable).where((0,o.eq)(h.threadTable.id,e));if(!r||"running"!==r.status)return null;let n=await a.select().from(h.threadWorkTable).where((0,o.eq)(h.threadWorkTable.threadId,e)).orderBy(i.sql`${h.threadWorkTable}.rowid`),s=new Set(n.filter(e=>"external"===e.state).map(e=>e.caller));for(let e of n)"queued"===e.state&&s.has(e.bot)&&(await a.update(h.threadWorkTable).set({state:"waiting"}).where((0,o.eq)(h.threadWorkTable.id,e.id)),e.state="waiting",t=!0);let d=n.filter(e=>"running"===e.state);if(d.length>=l.BOT_RUN.concurrent)return null;let u=n.find(e=>"queued"===e.state&&!d.some(t=>t.bot===e.bot));if(!u)return null;if(r.turns>=l.BOT_RUN.turns)return await a.update(h.threadWorkTable).set({state:"paused"}).where((0,o.and)((0,o.eq)(h.threadWorkTable.threadId,e),(0,o.eq)(h.threadWorkTable.state,"queued"))),null;let[c]=await a.update(h.threadWorkTable).set({state:"running",generation:u.generation+1}).where((0,o.eq)(h.threadWorkTable.id,u.id)).returning();return await a.update(h.threadTable).set({turns:r.turns+1}).where((0,o.eq)(h.threadTable.id,e)),c});return(a||t)&&B(),a}async function R(e){let t=await d.database.transaction(async t=>{await $(t,e);let a=await t.select().from(h.threadDeliveryTable).where((0,o.and)((0,o.eq)(h.threadDeliveryTable.workId,e.id),(0,o.eq)(h.threadDeliveryTable.consumed,!1))).orderBy(h.threadDeliveryTable.id);for(let r of a){let a=O(r);await y(t,e.threadId,{bot:e.bot,parent:e.id,role:"user",content:a,hidden:!r.visible}),await t.update(h.threadDeliveryTable).set({consumed:!0}).where((0,o.eq)(h.threadDeliveryTable.id,r.id))}return a.map(O)});return t.length&&B(),t}function O(e){return e.visible?(0,w.tagSpeaker)("The user"===e.speaker?"user":"thursday",e.text):`${e.speaker}:
93
93
 
@@ -1,3 +1,5 @@
1
- module.exports=[596410,e=>{"use strict";var t=e.i(527608);let a=(0,e.i(91264).serverRoute)(()=>(0,t.listSignIns)());e.s(["GET",0,a])},938811,e=>{"use strict";var t=e.i(747909),a=e.i(174017),n=e.i(996250),i=e.i(759756),r=e.i(561916),s=e.i(174677),o=e.i(869741),l=e.i(316795),u=e.i(487718),d=e.i(995169),c=e.i(47587),p=e.i(666012),h=e.i(570101),R=e.i(626937),g=e.i(10372),v=e.i(193695);e.i(52474);var w=e.i(600220);let f=new t.AppRouteRouteModule({definition:{kind:a.RouteKind.APP_ROUTE,page:"/api/signins/route",pathname:"/api/signins",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/signins/route.ts",nextConfigOutput:"standalone",userland:()=>e.r(596410),...{}}),{workAsyncStorage:m,workUnitAsyncStorage:C,serverHooks:E}=f;async function A(e,t,n){n.requestMeta&&(0,i.setRequestMeta)(e,n.requestMeta),f.isDev&&(0,i.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let m="/api/signins/route";m=m.replace(/\/index$/,"")||"/";let C=await f.prepare(e,t,{srcPage:m,multiZoneDraftMode:!1});if(!C)return t.statusCode=400,t.end("Bad Request"),null==n.waitUntil||n.waitUntil.call(n,Promise.resolve()),null;let{buildId:E,deploymentId:A,params:S,nextConfig:y,parsedUrl:x,isDraftMode:T,prerenderManifest:b,routerServerContext:I,isOnDemandRevalidate:P,revalidateOnlyGenerated:k,resolvedPathname:N,clientReferenceManifest:O,serverActionsManifest:_}=C,H=(0,o.normalizeAppPath)(m),q=!!(b.dynamicRoutes[H]||b.routes[N]),D=async()=>((null==I?void 0:I.render404)?await I.render404(e,t,x,!1):t.end("This page could not be found"),null);if(q&&!T){let e=!!b.routes[N],t=b.dynamicRoutes[H];if(t&&!1===t.fallback&&!e){if(y.adapterPath)return await D();throw new v.NoFallbackError}}let M=null;!q||f.isDev||T||(M="/index"===(M=N)?"/":M);let U=!0===f.isDev||!q,j=q&&!U;_&&O&&(0,s.setManifestsSingleton)({page:m,clientReferenceManifest:O,serverActionsManifest:_});let F=e.method||"GET",$=(0,r.getTracer)(),K=$.getActiveScopeSpan(),L=!!(null==I?void 0:I.isWrappedByNextServer),B=!!(0,i.getRequestMeta)(e,"minimalMode"),G=(0,i.getRequestMeta)(e,"incrementalCache")||await f.getIncrementalCache(e,y,b,B);null==G||G.resetRequestCache(),globalThis.__incrementalCache=G;let V={params:S,previewProps:b.preview,renderOpts:{experimental:{authInterrupts:!!y.experimental.authInterrupts,useCacheTimeout:y.experimental.useCacheTimeout},cacheComponents:!!y.cacheComponents,validationLevel:y.experimental.instantInsights.validationLevel,supportsDynamicResponse:U,incrementalCache:G,hmrRefreshHash:(0,i.getRequestMeta)(e,"hmrRefreshHash"),cacheLifeProfiles:y.cacheLife,staticPageGenerationTimeout:y.staticPageGenerationTimeout,waitUntil:n.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,a,n,i)=>f.onRequestError(e,t,n,i,I)},sharedContext:{buildId:E,deploymentId:A}},W=new l.NodeNextRequest(e),X=new l.NodeNextResponse(t),z=u.NextRequestAdapter.fromNodeNextRequest(W,(0,u.signalFromNodeResponse)(t)),J=async({previousCacheEntry:a})=>{try{if(!B&&P&&k&&!a)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let i=await f.handle(z,V);e.fetchMetrics=V.renderOpts.fetchMetrics;let r=V.renderOpts.pendingWaitUntil;r&&n.waitUntil&&(n.waitUntil(r),r=void 0);let s=V.renderOpts.collectedTags;if(!q)return await (0,p.sendResponse)(W,X,i,r),null;{let e=await i.blob(),t=(0,h.toNodeOutgoingHttpHeaders)(i.headers);s&&(t[g.NEXT_CACHE_TAGS_HEADER]=s),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let a=void 0!==V.renderOpts.collectedRevalidate&&!(V.renderOpts.collectedRevalidate>=g.INFINITE_CACHE)&&V.renderOpts.collectedRevalidate,n=void 0===V.renderOpts.collectedExpire||V.renderOpts.collectedExpire>=g.INFINITE_CACHE?!1!==a&&a>0?y.expireTime:void 0:V.renderOpts.collectedExpire;return{value:{kind:w.CachedRouteKind.APP_ROUTE,status:i.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:a,expire:n}}}}catch(t){throw(null==a?void 0:a.isStale)&&await f.onRequestError(e,t,{routerKind:"App Router",routePath:m,routeType:"route",revalidateReason:(0,c.getRevalidateReason)({isStaticGeneration:j,isOnDemandRevalidate:P})},!1,I),t}},Z=async(i,s)=>{try{var o,l;let i=await f.handleResponse({req:e,nextConfig:y,cacheKey:M,routeKind:a.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:b,isRoutePPREnabled:!1,isOnDemandRevalidate:P,revalidateOnlyGenerated:k,responseGenerator:J,waitUntil:n.waitUntil,isMinimalMode:B});if(!q)return;if((null==i||null==(o=i.value)?void 0:o.kind)!==w.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==i||null==(l=i.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});B||t.setHeader("x-nextjs-cache",P?"REVALIDATED":i.isMiss?"MISS":i.isStale?"STALE":"HIT"),T&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let r=(0,h.fromNodeOutgoingHttpHeaders)(i.value.headers);B&&q||r.delete(g.NEXT_CACHE_TAGS_HEADER),!i.cacheControl||t.getHeader("Cache-Control")||r.get("Cache-Control")||r.set("Cache-Control",(0,R.getCacheControlHeader)(i.cacheControl)),await (0,p.sendResponse)(W,X,new Response(i.value.body,{headers:r,status:i.value.status||200}));return}catch(t){if(t instanceof v.NoFallbackError||await f.onRequestError(e,t,{routerKind:"App Router",routePath:H,routeType:"route",revalidateReason:(0,c.getRevalidateReason)({isStaticGeneration:j,isOnDemandRevalidate:P})},!1,I),q)throw t;await (0,p.sendResponse)(W,X,new Response(null,{status:500}));return}finally{(()=>{if(!i)return;let e=t.statusCode;i.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(i.setStatus({code:r.SpanStatusCode.ERROR}),i.setAttribute("error.type",e.toString()));let a=$.getRootSpanAttributes();if(!a)return;if(a.get("next.span_type")!==d.BaseServerSpan.handleRequest)return console.warn(`Unexpected root span type '${a.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=a.get("next.route")||H,o=`${F} ${n}`;i.setAttributes({"next.route":n,"http.route":n,"next.span_name":o}),i.updateName(o),s&&s!==i&&(s.setAttribute("http.route",n),s.updateName(o))})()}};if(L&&K)await Z(K,void 0);else{let t=$.getActiveScopeSpan();await $.withPropagatedContext(e.headers,()=>$.trace(d.BaseServerSpan.handleRequest,{spanName:`${F} ${m}`,kind:r.SpanKind.SERVER,attributes:{"http.method":F,"http.target":e.url}},e=>Z(e,t)),void 0,!L)}}e.s(["handler",0,A,"patchFetch",0,function(){return(0,n.patchFetch)({workAsyncStorage:m,workUnitAsyncStorage:C})},"routeModule",0,f,"serverHooks",0,E,"workAsyncStorage",0,m,"workUnitAsyncStorage",0,C])},527608,824664,e=>{"use strict";var t=e.i(912714),a=e.i(750227),n=e.i(380690),i=e.i(687388);e.i(786025),e.i(640911);let r=e=>e.trim().toLowerCase().replace(/^[a-z]+:\/\//,"").replace(/^www\./,"").replace(/[/?#].*$/,"");e.s(["siteOf",0,r],824664);let s=(0,a.join)(i.DATA_DIR,i.PATHS.signIns),o=e=>(0,a.join)(s,`${encodeURIComponent(r(e))}.json`);async function l(e){try{return JSON.parse(await (0,t.readFile)(o(e),"utf8"))}catch{return null}}async function u(e){await (0,t.mkdir)(s,{recursive:!0}),await (0,t.writeFile)(o(e.site),JSON.stringify(e),{mode:384}),n.appEvents.emit({type:"signins"})}async function d(){let e=await (0,t.readdir)(s).catch(()=>[]);return(await Promise.all(e.filter(e=>e.endsWith(".json")).map(e=>l(decodeURIComponent(e.slice(0,-5)))))).flatMap(e=>e?[(({state:e,...t})=>t)(e)]:[]).sort((e,t)=>e.site.localeCompare(t.site))}async function c(e){let t=r(e.site),a=await l(t),n={site:t,account:e.account.trim()||t,bots:[...new Set([...a?.bots??[],e.bot])],asking:(a?.asking??[]).filter(t=>t!==e.bot),keptAt:new Date().toISOString(),usedAt:a?.usedAt??null,state:e.state};return await u(n),(({state:e,...t})=>t)(n)}async function p(e,t){let a=await l(e);if(!a)return{kind:"none",kept:(await d()).map(e=>e.site)};if(!a.bots.includes(t))return a.asking.includes(t)||await u({...a,asking:[...a.asking,t]}),{kind:"ask",signIn:(({state:e,...t})=>t)(a)};let n={...a,usedAt:new Date().toISOString()};return await u(n),{kind:"state",signIn:(({state:e,...t})=>t)(n),state:a.state}}e.s(["borrowSignIn",0,p,"keepSignIn",0,c,"listSignIns",0,d],527608)}];
1
+ module.exports=[596410,e=>{"use strict";var t=e.i(527608);let a=(0,e.i(91264).serverRoute)(()=>(0,t.listSignIns)());e.s(["GET",0,a])},938811,e=>{"use strict";var t=e.i(747909),a=e.i(174017),n=e.i(996250),i=e.i(759756),r=e.i(561916),s=e.i(174677),o=e.i(869741),l=e.i(316795),u=e.i(487718),d=e.i(995169),c=e.i(47587),p=e.i(666012),h=e.i(570101),w=e.i(626937),g=e.i(10372),R=e.i(193695);e.i(52474);var f=e.i(600220);let m=new t.AppRouteRouteModule({definition:{kind:a.RouteKind.APP_ROUTE,page:"/api/signins/route",pathname:"/api/signins",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/signins/route.ts",nextConfigOutput:"standalone",userland:()=>e.r(596410),...{}}),{workAsyncStorage:v,workUnitAsyncStorage:C,serverHooks:S}=m;async function E(e,t,n){n.requestMeta&&(0,i.setRequestMeta)(e,n.requestMeta),m.isDev&&(0,i.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let v="/api/signins/route";v=v.replace(/\/index$/,"")||"/";let C=await m.prepare(e,t,{srcPage:v,multiZoneDraftMode:!1});if(!C)return t.statusCode=400,t.end("Bad Request"),null==n.waitUntil||n.waitUntil.call(n,Promise.resolve()),null;let{buildId:S,deploymentId:E,params:y,nextConfig:A,parsedUrl:x,isDraftMode:I,prerenderManifest:T,routerServerContext:b,isOnDemandRevalidate:k,revalidateOnlyGenerated:N,resolvedPathname:O,clientReferenceManifest:P,serverActionsManifest:_}=C,H=(0,o.normalizeAppPath)(v),M=!!(T.dynamicRoutes[H]||T.routes[O]),U=async()=>((null==b?void 0:b.render404)?await b.render404(e,t,x,!1):t.end("This page could not be found"),null);if(M&&!I){let e=!!T.routes[O],t=T.dynamicRoutes[H];if(t&&!1===t.fallback&&!e){if(A.adapterPath)return await U();throw new R.NoFallbackError}}let q=null;!M||m.isDev||I||(q="/index"===(q=O)?"/":q);let D=!0===m.isDev||!M,j=M&&!D;_&&P&&(0,s.setManifestsSingleton)({page:v,clientReferenceManifest:P,serverActionsManifest:_});let $=e.method||"GET",F=(0,r.getTracer)(),L=F.getActiveScopeSpan(),K=!!(null==b?void 0:b.isWrappedByNextServer),G=!!(0,i.getRequestMeta)(e,"minimalMode"),W=(0,i.getRequestMeta)(e,"incrementalCache")||await m.getIncrementalCache(e,A,T,G);null==W||W.resetRequestCache(),globalThis.__incrementalCache=W;let B={params:y,previewProps:T.preview,renderOpts:{experimental:{authInterrupts:!!A.experimental.authInterrupts,useCacheTimeout:A.experimental.useCacheTimeout},cacheComponents:!!A.cacheComponents,validationLevel:A.experimental.instantInsights.validationLevel,supportsDynamicResponse:D,incrementalCache:W,hmrRefreshHash:(0,i.getRequestMeta)(e,"hmrRefreshHash"),cacheLifeProfiles:A.cacheLife,staticPageGenerationTimeout:A.staticPageGenerationTimeout,waitUntil:n.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,a,n,i)=>m.onRequestError(e,t,n,i,b)},sharedContext:{buildId:S,deploymentId:E}},J=new l.NodeNextRequest(e),V=new l.NodeNextResponse(t),X=u.NextRequestAdapter.fromNodeNextRequest(J,(0,u.signalFromNodeResponse)(t)),z=async({previousCacheEntry:a})=>{try{if(!G&&k&&N&&!a)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let i=await m.handle(X,B);e.fetchMetrics=B.renderOpts.fetchMetrics;let r=B.renderOpts.pendingWaitUntil;r&&n.waitUntil&&(n.waitUntil(r),r=void 0);let s=B.renderOpts.collectedTags;if(!M)return await (0,p.sendResponse)(J,V,i,r),null;{let e=await i.blob(),t=(0,h.toNodeOutgoingHttpHeaders)(i.headers);s&&(t[g.NEXT_CACHE_TAGS_HEADER]=s),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let a=void 0!==B.renderOpts.collectedRevalidate&&!(B.renderOpts.collectedRevalidate>=g.INFINITE_CACHE)&&B.renderOpts.collectedRevalidate,n=void 0===B.renderOpts.collectedExpire||B.renderOpts.collectedExpire>=g.INFINITE_CACHE?!1!==a&&a>0?A.expireTime:void 0:B.renderOpts.collectedExpire;return{value:{kind:f.CachedRouteKind.APP_ROUTE,status:i.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:a,expire:n}}}}catch(t){throw(null==a?void 0:a.isStale)&&await m.onRequestError(e,t,{routerKind:"App Router",routePath:v,routeType:"route",revalidateReason:(0,c.getRevalidateReason)({isStaticGeneration:j,isOnDemandRevalidate:k})},!1,b),t}},Y=async(i,s)=>{try{var o,l;let i=await m.handleResponse({req:e,nextConfig:A,cacheKey:q,routeKind:a.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:T,isRoutePPREnabled:!1,isOnDemandRevalidate:k,revalidateOnlyGenerated:N,responseGenerator:z,waitUntil:n.waitUntil,isMinimalMode:G});if(!M)return;if((null==i||null==(o=i.value)?void 0:o.kind)!==f.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==i||null==(l=i.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});G||t.setHeader("x-nextjs-cache",k?"REVALIDATED":i.isMiss?"MISS":i.isStale?"STALE":"HIT"),I&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let r=(0,h.fromNodeOutgoingHttpHeaders)(i.value.headers);G&&M||r.delete(g.NEXT_CACHE_TAGS_HEADER),!i.cacheControl||t.getHeader("Cache-Control")||r.get("Cache-Control")||r.set("Cache-Control",(0,w.getCacheControlHeader)(i.cacheControl)),await (0,p.sendResponse)(J,V,new Response(i.value.body,{headers:r,status:i.value.status||200}));return}catch(t){if(t instanceof R.NoFallbackError||await m.onRequestError(e,t,{routerKind:"App Router",routePath:H,routeType:"route",revalidateReason:(0,c.getRevalidateReason)({isStaticGeneration:j,isOnDemandRevalidate:k})},!1,b),M)throw t;await (0,p.sendResponse)(J,V,new Response(null,{status:500}));return}finally{(()=>{if(!i)return;let e=t.statusCode;i.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(i.setStatus({code:r.SpanStatusCode.ERROR}),i.setAttribute("error.type",e.toString()));let a=F.getRootSpanAttributes();if(!a)return;if(a.get("next.span_type")!==d.BaseServerSpan.handleRequest)return console.warn(`Unexpected root span type '${a.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=a.get("next.route")||H,o=`${$} ${n}`;i.setAttributes({"next.route":n,"http.route":n,"next.span_name":o}),i.updateName(o),s&&s!==i&&(s.setAttribute("http.route",n),s.updateName(o))})()}};if(K&&L)await Y(L,void 0);else{let t=F.getActiveScopeSpan();await F.withPropagatedContext(e.headers,()=>F.trace(d.BaseServerSpan.handleRequest,{spanName:`${$} ${v}`,kind:r.SpanKind.SERVER,attributes:{"http.method":$,"http.target":e.url}},e=>Y(e,t)),void 0,!K)}}e.s(["handler",0,E,"patchFetch",0,function(){return(0,n.patchFetch)({workAsyncStorage:v,workUnitAsyncStorage:C})},"routeModule",0,m,"serverHooks",0,S,"workAsyncStorage",0,v,"workUnitAsyncStorage",0,C])},527608,824664,e=>{"use strict";var t=e.i(912714),a=e.i(750227),n=e.i(380690),i=e.i(687388),r=e.i(786025);e.i(640911);let s=e=>e.trim().toLowerCase().replace(/^[a-z]+:\/\//,"").replace(/^www\./,"").replace(/[/?#].*$/,"");e.s(["siteOf",0,s],824664);let o=(0,a.join)(i.DATA_DIR,i.PATHS.signIns),l=e=>(0,a.join)(o,`${encodeURIComponent(s(e))}.json`);async function u(e){try{return JSON.parse(await (0,t.readFile)(l(e),"utf8"))}catch{return null}}async function d(e){await (0,t.mkdir)(o,{recursive:!0}),await (0,t.writeFile)(l(e.site),JSON.stringify(e),{mode:384}),n.appEvents.emit({type:"signins"})}async function c(){let e=await (0,t.readdir)(o).catch(()=>[]);return(await Promise.all(e.filter(e=>e.endsWith(".json")).map(e=>u(decodeURIComponent(e.slice(0,-5)))))).flatMap(e=>e?[(({state:e,...t})=>t)(e)]:[]).sort((e,t)=>e.site.localeCompare(t.site))}async function p(e){let t=s(e.site),a=await u(t),n={site:t,account:e.account.trim()||t,bots:[...new Set([...a?.bots??[],e.bot])],asking:(a?.asking??[]).filter(t=>t!==e.bot),keptAt:new Date().toISOString(),usedAt:a?.usedAt??null,state:e.state};return await d(n),(({state:e,...t})=>t)(n)}async function h(e,t){let a=await u(e);if(!a)return{kind:"none",kept:(await c()).map(e=>e.site)};if(!a.bots.includes(t))return a.asking.includes(t)||await d({...a,asking:[...a.asking,t]}),{kind:"ask",signIn:(({state:e,...t})=>t)(a)};let n={...a,usedAt:new Date().toISOString()};return await d(n),{kind:"state",signIn:(({state:e,...t})=>t)(n),state:a.state}}let w=e=>`${e.name}
2
+ ${e.domain}
3
+ ${e.path}`;async function g(e){let a,n=await (0,t.readdir)(o).catch(()=>[]);if(!n.some(e=>e.endsWith(".json")))return;let i=await (0,r.openWorkspace)(),s=(0,r.jobShellEnv)(e),{browsers:l}=JSON.parse((await i.exec("playwright-cli list --json",{env:s,timeoutMs:15e3})).stdout||"{}"),c=l?.find(e=>e.name===s.PLAYWRIGHT_CLI_SESSION);if(!c||c.attached)return;let p=`.playwright-cli/state-${crypto.randomUUID()}.json`;try{let e=await i.exec(`mkdir -p .playwright-cli && playwright-cli state-save ${p}`,{env:s,timeoutMs:3e4});if(0!==e.exitCode)return;let t=JSON.parse(await i.readFile(p,"utf-8"));a=new Map((t.cookies??[]).map(e=>[w(e),e]))}finally{await i.exec(`rm -f ${p}`)}for(let e of n){if(!e.endsWith(".json"))continue;let t=await u(decodeURIComponent(e.slice(0,-5))),n=t?.state;if(!t||!n?.cookies)continue;let i=!1,r=n.cookies.map(e=>{let t=a.get(w(e));return t&&JSON.stringify(t)!==JSON.stringify(e)?(i=!0,t):e});i&&await d({...t,state:{...n,cookies:r}})}}e.s(["borrowSignIn",0,h,"keepSignIn",0,p,"listSignIns",0,c,"renewSignIns",0,g],527608)}];
2
4
 
3
5
  //# sourceMappingURL=_1i350l5._.js.map
@@ -1,6 +1,6 @@
1
- module.exports=[102473,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__18-2tsq._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(232347)))},130022,e=>{e.v(s=>Promise.all(["server/chunks/config_ts_1g4sz5o._.js"].map(s=>e.l(s))).then(()=>s(333925)))},266965,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__1orn-5b._.js","server/chunks/_0khihjk._.js"].map(s=>e.l(s))).then(()=>s(946280)))},171772,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__1ndi14y._.js"].map(s=>e.l(s))).then(()=>s(973589)))},242792,e=>{e.v(s=>Promise.all(["server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1y49572._.js","server/chunks/_10tkr26._.js","server/chunks/[root-of-the-server]__0nr-v8s._.js","server/chunks/_1y8w80a._.js","server/chunks/lib_logger_ts_07e65t5._.js","server/chunks/_1kg70wc._.js","server/chunks/_1ogqovh._.js"].map(s=>e.l(s))).then(()=>s(799791)))},327784,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__0mrk2it._.js","server/chunks/_1tpr507._.js","server/chunks/features_0rfvely._.js","server/chunks/_05h2cii._.js","server/chunks/[root-of-the-server]__1wnzmx9._.js","server/chunks/_10tkr26._.js","server/chunks/_136j09a._.js","server/chunks/_1kg70wc._.js","server/chunks/features_0hdaci0._.js","server/chunks/_1jn-aep._.js","server/chunks/_1zxp-p6._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(49002)))},566024,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__0h_x6q6._.js","server/chunks/_05h2cii._.js","server/chunks/_1e48czp._.js","server/chunks/_1y8w80a._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(1363)))},975158,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__0mrk2it._.js","server/chunks/_1tpr507._.js","server/chunks/features_0rfvely._.js","server/chunks/features_0hdaci0._.js","server/chunks/_1zxp-p6._.js","server/chunks/[root-of-the-server]__1wnzmx9._.js","server/chunks/_0x-ej3f._.js","server/chunks/_1kg70wc._.js","server/chunks/lib_logger_ts_07e65t5._.js","server/chunks/_136j09a._.js","server/chunks/_05h2cii._.js","server/chunks/_1jn-aep._.js","server/chunks/_10tkr26._.js"].map(s=>e.l(s))).then(()=>s(312485)))},569286,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__1ygplx1._.js","server/chunks/_1tpr507._.js","server/chunks/features_0rfvely._.js","server/chunks/_05h2cii._.js","server/chunks/[root-of-the-server]__1wnzmx9._.js","server/chunks/_10tkr26._.js","server/chunks/_1jn-aep._.js","server/chunks/_1y8w80a._.js","server/chunks/features_0hdaci0._.js","server/chunks/_1kg70wc._.js","server/chunks/_1zxp-p6._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(733184)))},741548,e=>{e.v(s=>Promise.all(["server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1y49572._.js","server/chunks/lib_logger_ts_07e65t5._.js","server/chunks/[root-of-the-server]__0209ah4._.js"].map(s=>e.l(s))).then(()=>s(379651)))},917723,e=>{e.v(s=>Promise.all(["server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1y49572._.js","server/chunks/lib_logger_ts_07e65t5._.js","server/chunks/_0f6ts7z._.js","server/chunks/_1e48czp._.js","server/chunks/_1y8w80a._.js","server/chunks/[root-of-the-server]__12iddfq._.js","server/chunks/features_0hdaci0._.js"].map(s=>e.l(s))).then(()=>s(520401)))},51833,e=>{e.v(s=>Promise.all(["server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1y49572._.js","server/chunks/lib_logger_ts_07e65t5._.js","server/chunks/[root-of-the-server]__1cjxw0-._.js"].map(s=>e.l(s))).then(()=>s(871096)))},482438,e=>{"use strict";async function s(){let{APP_DIR:s,APP_NAME:r,DATA_DIR:_,DB_FILE_NAME:t,WORKSPACE_KEEP:o}=await e.A(130022),{logger:n}=await e.A(415568),{migrateDatabase:a}=await e.A(266965);await a().catch(e=>{let s=t.replace(/^file:/,"");n.error(`Cannot migrate ${s}`),console.error(` ${e instanceof Error?e.message:e}
1
+ module.exports=[102473,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__18-2tsq._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(232347)))},130022,e=>{e.v(s=>Promise.all(["server/chunks/config_ts_1g4sz5o._.js"].map(s=>e.l(s))).then(()=>s(333925)))},266965,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__1orn-5b._.js","server/chunks/_0khihjk._.js"].map(s=>e.l(s))).then(()=>s(946280)))},171772,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__1ndi14y._.js"].map(s=>e.l(s))).then(()=>s(973589)))},242792,e=>{e.v(s=>Promise.all(["server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1y49572._.js","server/chunks/_10tkr26._.js","server/chunks/[root-of-the-server]__0nr-v8s._.js","server/chunks/_1y8w80a._.js","server/chunks/lib_logger_ts_07e65t5._.js","server/chunks/_1kg70wc._.js","server/chunks/_1ogqovh._.js"].map(s=>e.l(s))).then(()=>s(799791)))},327784,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__0mrk2it._.js","server/chunks/features_0rfvely._.js","server/chunks/_1tpr507._.js","server/chunks/_05h2cii._.js","server/chunks/[root-of-the-server]__1wnzmx9._.js","server/chunks/_10tkr26._.js","server/chunks/_1jn-aep._.js","server/chunks/_1kg70wc._.js","server/chunks/features_0hdaci0._.js","server/chunks/_136j09a._.js","server/chunks/_1zxp-p6._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(49002)))},566024,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__0h_x6q6._.js","server/chunks/_05h2cii._.js","server/chunks/_1e48czp._.js","server/chunks/_1y8w80a._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(1363)))},975158,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__0mrk2it._.js","server/chunks/features_0rfvely._.js","server/chunks/_1tpr507._.js","server/chunks/_10tkr26._.js","server/chunks/_1zxp-p6._.js","server/chunks/[root-of-the-server]__1wnzmx9._.js","server/chunks/_1jn-aep._.js","server/chunks/_1kg70wc._.js","server/chunks/features_0hdaci0._.js","server/chunks/_0x-ej3f._.js","server/chunks/_05h2cii._.js","server/chunks/_15740dw._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(312485)))},569286,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__1ygplx1._.js","server/chunks/features_0rfvely._.js","server/chunks/_1tpr507._.js","server/chunks/_05h2cii._.js","server/chunks/[root-of-the-server]__1wnzmx9._.js","server/chunks/_10tkr26._.js","server/chunks/_1jn-aep._.js","server/chunks/_1kg70wc._.js","server/chunks/features_0hdaci0._.js","server/chunks/_1y8w80a._.js","server/chunks/_1zxp-p6._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(733184)))},741548,e=>{e.v(s=>Promise.all(["server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1y49572._.js","server/chunks/lib_logger_ts_07e65t5._.js","server/chunks/[root-of-the-server]__0209ah4._.js"].map(s=>e.l(s))).then(()=>s(379651)))},917723,e=>{e.v(s=>Promise.all(["server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1y49572._.js","server/chunks/lib_logger_ts_07e65t5._.js","server/chunks/_0f6ts7z._.js","server/chunks/_1e48czp._.js","server/chunks/_1y8w80a._.js","server/chunks/[root-of-the-server]__12iddfq._.js","server/chunks/features_0hdaci0._.js"].map(s=>e.l(s))).then(()=>s(520401)))},51833,e=>{e.v(s=>Promise.all(["server/chunks/node_modules_consola_dist_chunks_prompt_mjs_1y49572._.js","server/chunks/lib_logger_ts_07e65t5._.js","server/chunks/[root-of-the-server]__1cjxw0-._.js"].map(s=>e.l(s))).then(()=>s(871096)))},482438,e=>{"use strict";async function s(){let{APP_DIR:s,APP_NAME:r,DATA_DIR:_,DB_FILE_NAME:t,WORKSPACE_KEEP:o}=await e.A(130022),{logger:n}=await e.A(415568),{migrateDatabase:a}=await e.A(266965);await a().catch(e=>{let s=t.replace(/^file:/,"");n.error(`Cannot migrate ${s}`),console.error(` ${e instanceof Error?e.message:e}
2
2
  Removing it starts over with an empty one. API keys, bots, connectors, calls, threads and memory go with it; the workspace and skills stay.
3
3
  rm "${s}" "${s}-wal" "${s}-shm"
4
- `),process.exit(65)});let{ensureRootNotes:h}=await e.A(566024);await h();let{installGuide:c}=await e.A(171772);await c().catch(e=>n.error("install guide",e));let{sweepJobFiles:v,sweepThreads:i}=await e.A(327784);await i();let l=()=>void v().catch(e=>n.error("sweep job files",e));l(),setInterval(l,o.sweepEveryMs).unref();let{sweepCalls:u}=await e.A(917723);await u();let{presence:k}=await e.A(102473),{pauseThreads:j,resumeStoppedThreads:m}=await e.A(327784),{readKeepWorkingOn:w}=await e.A(242792);k.onGone(()=>{(async()=>{await w()?n.info("browser gone — work goes on"):(n.info("browser gone — stopping what was running"),await j("The browser closed while this was running.",!0)),await u()})().catch(e=>n.error("browser gone",e))}),k.onBack(()=>{m().catch(e=>n.error("resume threads",e))});let{startRoutineClock:p}=await e.A(569286);p();let{adoptKeptSessions:g}=await e.A(741548);await g().catch(e=>n.error("adopt kept sessions",e));let{startReach:f}=await e.A(975158);if(f().catch(e=>n.error("start reach",e)),process.env.NEXT_MANUAL_SIG_HANDLE){let e=!1;for(let[s,r]of[["SIGINT",130],["SIGTERM",143]])process.on(s,()=>{e||(e=!0,n.info(`${s} — parking what was running`),Promise.race([j("The server was shut down while this was running.").catch(e=>n.error("pause threads",e)),new Promise(e=>setTimeout(e,3e3))]).finally(()=>process.exit(r)))})}n.info(`${r} is up — app ${s}, data ${_}`);let{ensureBrowser:d}=await e.A(51833);d().catch(e=>n.debug("browser fetch",e))}e.s(["boot",0,s])},415568,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__0sm5xvm._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(938281)))}];
4
+ `),process.exit(65)});let{ensureRootNotes:h}=await e.A(566024);await h();let{installGuide:c}=await e.A(171772);await c().catch(e=>n.error("install guide",e));let{sweepJobFiles:v,sweepThreads:i}=await e.A(327784);await i();let l=()=>void v().catch(e=>n.error("sweep job files",e));l(),setInterval(l,o.sweepEveryMs).unref();let{sweepCalls:u}=await e.A(917723);await u();let{presence:k}=await e.A(102473),{pauseThreads:j,resumeStoppedThreads:w}=await e.A(327784),{readKeepWorkingOn:m}=await e.A(242792);k.onGone(()=>{(async()=>{await m()?n.info("browser gone — work goes on"):(n.info("browser gone — stopping what was running"),await j("The browser closed while this was running.",!0)),await u()})().catch(e=>n.error("browser gone",e))}),k.onBack(()=>{w().catch(e=>n.error("resume threads",e))});let{startRoutineClock:p}=await e.A(569286);p();let{adoptKeptSessions:g}=await e.A(741548);await g().catch(e=>n.error("adopt kept sessions",e));let{startReach:f}=await e.A(975158);if(f().catch(e=>n.error("start reach",e)),process.env.NEXT_MANUAL_SIG_HANDLE){let e=!1;for(let[s,r]of[["SIGINT",130],["SIGTERM",143]])process.on(s,()=>{e||(e=!0,n.info(`${s} — parking what was running`),Promise.race([j("The server was shut down while this was running.").catch(e=>n.error("pause threads",e)),new Promise(e=>setTimeout(e,3e3))]).finally(()=>process.exit(r)))})}n.info(`${r} is up — app ${s}, data ${_}`);let{ensureBrowser:d}=await e.A(51833);d().catch(e=>n.debug("browser fetch",e))}e.s(["boot",0,s])},415568,e=>{e.v(s=>Promise.all(["server/chunks/[root-of-the-server]__0sm5xvm._.js","server/chunks/lib_logger_ts_07e65t5._.js"].map(s=>e.l(s))).then(()=>s(938281)))}];
5
5
 
6
6
  //# sourceMappingURL=_1jc5g4p._.js.map
@@ -71,7 +71,7 @@ ${(0,a.botGuideLine)()}`};e.s(["buildThreadOpening",0,function(e){if(e.routine){
71
71
 
72
72
  ${e.request.trim()}`}]}let t="user"===e.from?"The user":"Thursday";return[{type:"text",text:`You are ${e.bot}. ${t} hands you this thread${"user"===e.from?" on screen":" during a call"}.`},{type:"text",text:`## ${t} → ${e.bot}: the job
73
73
 
74
- ${e.request.trim()}`}]},"loadBotPrompt",0,w]),r()}catch(e){r(e)}},!1),636608,e=>{"use strict";var t=e.i(489938),r=e.i(588762),o=e.i(333925),n=e.i(51083),a=e.i(293822),i=e.i(900533),s=e.i(938281),l=e.i(610150),u=e.i(64774);let d=(e=new Date)=>`${(0,t.format)(e,"yyyy-MM-dd (EEE) HH:mm")} ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,c=(e=new Date)=>`**Now**: ${d(e)}`,p=e=>`${(0,t.format)(e,"yyyy-MM-dd (EEE) HH:mm")} (${(0,r.formatDistanceToNowStrict)(e,{addSuffix:!0})})`,h={[n.STUDIO_TOOLS.generate_image]:"images",[n.STUDIO_TOOLS.generate_speech]:"speech",[n.STUDIO_TOOLS.transcribe]:"transcription",[n.STUDIO_TOOLS.generate_video]:"video"};e.s(["botWorkHead",0,function(e,o){let n=(0,r.formatDistanceToNowStrict)(e.updatedAt,{addSuffix:!0}),a="running"===e.status?`running, last moved ${n}`:e.asking?`waiting on the user's answer since ${n}`:"waiting"===e.status?`stopped ${n}, not finished`:`${"done"===e.status?"ended":"stopped by the user"} ${(0,t.format)(e.updatedAt,"yyyy-MM-dd")}`;return`"${e.label}" — ${e.owner===o?"yours":`${e.owner}'s`} — ${a}`},"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 ${n.TOOL_NAMES.end_call} tool.`,"callStamp",0,p,"carriedLines",0,(e,t={})=>e.map(e=>`- ${e.text} \xb7 ${e.path}${!1===t.ids?"":` #${e.id}`}`).join("\n"),"clockNow",0,d,"conversationLines",0,e=>e.map(e=>"tool"===e.role?`you → ${e.tool??"tool"}`:`${"user"===e.role?"user":"you"}: ${e.text}`).join("\n"),"expandedFacts",0,function(e,t){let r=e.filter(e=>t.has(e.id)),n=e.filter(e=>!t.has(e.id)),a=Math.max(0,o.MEMORY_LIMITS.expanded-r.length),i=new Set([...r,...n.slice(Math.max(0,n.length-a))].map(e=>e.id)),s=e.filter(e=>i.has(e.id));return{shown:s,hidden:e.length-s.length}},"logPromptSize",0,function(e,t){let r=(0,l.sectionTokens)(t),n=r.reduce((e,t)=>e+t.tokens,0);s.logger.debug(`${e} prompt ${n} tokens — ${r.map(e=>`${e.name} ${e.tokens}`).join(", ")}`);let a=r[0];n>o.PROMPT_BUDGET&&a&&s.logger.warn(`${e} prompt is ${n} tokens, over ${o.PROMPT_BUDGET}: ${a.name} carries ${a.tokens} of it. Every call and every job pays this.`)},"mcpToolLines",0,function(e){let t=new Map;for(let r of e){let e=t.get(r.server);e?e.push(r.name):t.set(r.server,[r.name])}return[...t].map(([e,t])=>`- **${e}**: ${t.join(", ")}`).join("\n")},"noteLines",0,function(e,t=!1){return e.length?e.map(e=>{var r;let o,n=e.aliases?.length?` ${e.aliases.map(e=>`"${e}"`).join(" ")}`:"",a=t?` \xb7 ${r=e.lastSeenAt,(o=Math.floor((Date.now()-(0,i.toDate)(r).getTime())/864e5))>=365?`${Math.floor(o/365)}y`:o>=30?`${Math.floor(o/30)}mo`:`${Math.max(o,0)}d`}`:"";return`- ${e.path} — ${e.description?.trim()} (${e.factCount})${n}${a}`}).join("\n"):"(nothing saved yet)"},"nowLine",0,c,"reachNames",0,function(e,t){let r=t.map(e=>e.server===o.STUDIO_SERVER?h[e.name]??e.name:e.server);return[...new Set([...e.map(e=>e.name),...r])].join(", ")},"recentCallLines",0,function(e,t){let r=[],i=0;e:for(let s=e.length-1;s>=0;s--){let d=e[s];for(let e=d.turns.length-1;e>=0;e--){let s=function(e,t){if("tool"!==e.role)return`${"user"===e.role?"user":"you"}: ${e.text}`;let r=(0,a.searchOf)(e.tool,e.text);if(r){let t=[...new Set(r.sources.flatMap(e=>{try{return[new URL(e.url).hostname.replace(/^www\./,"")]}catch{return[]}}))];return`you → ${e.tool} "${(0,u.clip)(r.query??"",o.PROMPT_LINE.toolArgs)}"${t.length?` — ${t.join(", ")}`:""}`}let i=`you → ${e.tool??"tool"} ${(0,u.clip)(e.text,o.PROMPT_LINE.toolArgs)}`;if(e.tool!==n.TOOL_NAMES.thread_start)return i;let s=(0,a.startedLabel)(e.tool,e.text),l=s?t.jobs?.find(e=>e.label===s):void 0;if(!l)return i;let d=l.outcome?`: ${(0,u.clip)(l.outcome,o.PROMPT_LINE.jobOutcome)}`:"";return`you → ${e.tool} "${l.label}" (${l.id}) — ${l.status}${d}`}(d.turns[e],d),c=(0,l.estimateTokens)(s)+3;if(i+c>t&&r.length)break e;i+=c,r.push({call:d,line:s})}}r.reverse();let s=[],d=null;for(let{call:e,line:t}of r)e!==d&&(d=e,s.push(`### ${p(e.startedAt)}`)),s.push(t);return s.join("\n")},"saidStamp",0,e=>(0,t.format)(e,"yyyy-MM-dd (EEE) HH:mm"),"skillLines",0,(e,t={})=>e.map(e=>{var r;let n,a;return`- **${e.name}**: ${t.short?(r=e.description,n=o.PROMPT_LINE.skill,(a=r.trim().split(/(?<=[.。])\s|\n/)[0].trim()).length>n?`${a.slice(0,n).trim()}…`:a):e.description}`}).join("\n"),"thursdayIdentity",0,(e=new Date)=>`You are Thursday, this user's own personal assistant, on their side, modeled on Friday, the AI in *Iron Man*. ${c(e)}
74
+ ${e.request.trim()}`}]},"loadBotPrompt",0,w]),r()}catch(e){r(e)}},!1),636608,e=>{"use strict";var t=e.i(489938),r=e.i(588762),o=e.i(333925),n=e.i(51083),a=e.i(293822),i=e.i(900533),s=e.i(938281),l=e.i(610150),u=e.i(64774);let d=(e=new Date)=>`${(0,t.format)(e,"yyyy-MM-dd (EEE) HH:mm")} ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,c=(e=new Date)=>`**Now**: ${d(e)}`,p=e=>`${(0,t.format)(e,"yyyy-MM-dd (EEE) HH:mm")} (${(0,r.formatDistanceToNowStrict)(e,{addSuffix:!0})})`,h={[n.STUDIO_TOOLS.generate_image]:"images",[n.STUDIO_TOOLS.generate_speech]:"speech",[n.STUDIO_TOOLS.transcribe]:"transcription",[n.STUDIO_TOOLS.generate_video]:"video"};e.s(["botWorkHead",0,function(e,o){let n=(0,r.formatDistanceToNowStrict)(e.updatedAt,{addSuffix:!0}),a="running"===e.status?`running, last moved ${n}`:e.asking?`waiting on the user's answer since ${n}`:"waiting"===e.status?`stopped ${n}, not finished`:`${"done"===e.status?"ended":"stopped by the user"} ${(0,t.format)(e.updatedAt,"yyyy-MM-dd")}`;return`"${e.label}" — ${e.owner===o?"yours":`${e.owner}'s`} — ${a}`},"callStamp",0,p,"carriedLines",0,(e,t={})=>e.map(e=>`- ${e.text} \xb7 ${e.path}${!1===t.ids?"":` #${e.id}`}`).join("\n"),"clockNow",0,d,"conversationLines",0,e=>e.map(e=>"tool"===e.role?`you → ${e.tool??"tool"}`:`${"user"===e.role?"user":"you"}: ${e.text}`).join("\n"),"expandedFacts",0,function(e,t){let r=e.filter(e=>t.has(e.id)),n=e.filter(e=>!t.has(e.id)),a=Math.max(0,o.MEMORY_LIMITS.expanded-r.length),i=new Set([...r,...n.slice(Math.max(0,n.length-a))].map(e=>e.id)),s=e.filter(e=>i.has(e.id));return{shown:s,hidden:e.length-s.length}},"logPromptSize",0,function(e,t){let r=(0,l.sectionTokens)(t),n=r.reduce((e,t)=>e+t.tokens,0);s.logger.debug(`${e} prompt ${n} tokens — ${r.map(e=>`${e.name} ${e.tokens}`).join(", ")}`);let a=r[0];n>o.PROMPT_BUDGET&&a&&s.logger.warn(`${e} prompt is ${n} tokens, over ${o.PROMPT_BUDGET}: ${a.name} carries ${a.tokens} of it. Every call and every job pays this.`)},"mcpToolLines",0,function(e){let t=new Map;for(let r of e){let e=t.get(r.server);e?e.push(r.name):t.set(r.server,[r.name])}return[...t].map(([e,t])=>`- **${e}**: ${t.join(", ")}`).join("\n")},"noteLines",0,function(e,t=!1){return e.length?e.map(e=>{var r;let o,n=e.aliases?.length?` ${e.aliases.map(e=>`"${e}"`).join(" ")}`:"",a=t?` \xb7 ${r=e.lastSeenAt,(o=Math.floor((Date.now()-(0,i.toDate)(r).getTime())/864e5))>=365?`${Math.floor(o/365)}y`:o>=30?`${Math.floor(o/30)}mo`:`${Math.max(o,0)}d`}`:"";return`- ${e.path} — ${e.description?.trim()} (${e.factCount})${n}${a}`}).join("\n"):"(nothing saved yet)"},"nowLine",0,c,"reachNames",0,function(e,t){let r=t.map(e=>e.server===o.STUDIO_SERVER?h[e.name]??e.name:e.server);return[...new Set([...e.map(e=>e.name),...r])].join(", ")},"recentCallLines",0,function(e,t){let r=[],i=0;e:for(let s=e.length-1;s>=0;s--){let d=e[s];for(let e=d.turns.length-1;e>=0;e--){let s=function(e,t){if("tool"!==e.role)return`${"user"===e.role?"user":"you"}: ${e.text}`;let r=(0,a.searchOf)(e.tool,e.text);if(r){let t=[...new Set(r.sources.flatMap(e=>{try{return[new URL(e.url).hostname.replace(/^www\./,"")]}catch{return[]}}))];return`you → ${e.tool} "${(0,u.clip)(r.query??"",o.PROMPT_LINE.toolArgs)}"${t.length?` — ${t.join(", ")}`:""}`}let i=`you → ${e.tool??"tool"} ${(0,u.clip)(e.text,o.PROMPT_LINE.toolArgs)}`;if(e.tool!==n.TOOL_NAMES.thread_start)return i;let s=(0,a.startedLabel)(e.tool,e.text),l=s?t.jobs?.find(e=>e.label===s):void 0;if(!l)return i;let d=l.outcome?`: ${(0,u.clip)(l.outcome,o.PROMPT_LINE.jobOutcome)}`:"";return`you → ${e.tool} "${l.label}" (${l.id}) — ${l.status}${d}`}(d.turns[e],d),c=(0,l.estimateTokens)(s)+3;if(i+c>t&&r.length)break e;i+=c,r.push({call:d,line:s})}}r.reverse();let s=[],d=null;for(let{call:e,line:t}of r)e!==d&&(d=e,s.push(`### ${p(e.startedAt)}`)),s.push(t);return s.join("\n")},"saidStamp",0,e=>(0,t.format)(e,"yyyy-MM-dd (EEE) HH:mm"),"skillLines",0,(e,t={})=>e.map(e=>{var r;let n,a;return`- **${e.name}**: ${t.short?(r=e.description,n=o.PROMPT_LINE.skill,(a=r.trim().split(/(?<=[.。])\s|\n/)[0].trim()).length>n?`${a.slice(0,n).trim()}…`:a):e.description}`}).join("\n"),"thursdayIdentity",0,(e=new Date)=>`You are Thursday, this user's own personal assistant, on their side, modeled on Friday, the AI in *Iron Man*. ${c(e)}
75
75
 
76
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,e=>({crowded:e.reduce((e,t)=>e+t.factCount,0)>o.MEMORY_LIMITS.facts,heavy:e.filter(e=>e.factCount>o.MEMORY_LIMITS.factsPerNote)})])},423620,e=>e.a(async(t,r)=>{try{var o=e.i(691296),n=e.i(749906),a=e.i(333925),i=e.i(636608),s=e.i(51083),l=e.i(951056),u=e.i(600690),d=e.i(5509),c=e.i(64774),p=t([d]);[d]=p.then?(await p)():p;let m=n.string().describe("The thread, by its label or its id."),g={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:n.object({bot:n.string().describe("A name from the bot list."),request:n.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:n.string().describe("Two or three words naming the thread, in the user's language. Used on screen and said out loud.")})},f={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:n.object({thread:m,words:n.string().describe("What to tell its bot, in the user's language and words.")})},y={description:`Answer a question a bot asked the user. Only for a question that is waiting; anything else said to a thread is \`${s.TOOL_NAMES.thread_tell}\`.`,parameters:n.object({thread:m,bot:n.string().describe("The bot that asked."),answer:n.string().describe("The user's answer, in their words.")})},v={description:`Read threads as they are now. "all" lists up to ${a.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:n.object({thread:n.string().describe('"all", or one thread by its label or its id.')})},b={description:"Stop a thread for good. It cannot be taken back.",parameters:n.object({thread:m})},_={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:n.object({thread:m})},w={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:n.object({thread:m})},z={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:u.RoomMessageSchema.extend({kind:u.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:u.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:n.string().trim().min(1).describe("Choose a bot from the roster, or Thursday to reach the user."),text:n.string().trim().min(1).describe("Write the message and include the context the recipient needs."),replyTo:n.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:n.object({id:n.string().describe("The id in brackets on its line under Your other threads.")})};async function h(e,t){let r=await (0,d.listBotWork)(e,t),n=[...r.open,...r.recent];if(!n.some(e=>e.cut))return{};let u=new Set;return{[s.TOOL_NAMES.thread_recall]:(0,o.tool)({description:x.description,inputSchema:x.parameters,execute:async({id:t})=>{let r=t.trim().replace(/^\[|\]$/g,"").toLowerCase(),o=n.find(e=>r.length>=4&&(e.id.startsWith(r)||e.label.toLowerCase()===r));if(!o)return`No thread "${t}" on your list. The ids there: ${n.filter(e=>e.cut).map(e=>(0,l.workHandle)(e.id)).join(", ")}.`;if(!o.cut)return"Its line already shows all of it.";if(u.has(o.id))return"Already opened above, this turn.";if(u.size>=a.BOT_WORK.reads)return`${a.BOT_WORK.reads} threads are open already this turn. Carry on with what you have.`;u.add(o.id);let s=await (0,d.readBotAsk)(e,o),p=o.said??"";return[(0,i.botWorkHead)(o,e),s?`You were asked: ${(0,c.clip)(s,a.BOT_WORK.asked)}`:"",`Your last words there:
77
77
  ${p.length>a.BOT_WORK.readChars?`${p.slice(0,a.BOT_WORK.readChars)}
@@ -97,10 +97,10 @@ Every command is a new shell: \`cd\`, exported variables and an activated venv a
97
97
 
98
98
  Nothing is watching it. A command that stops to ask never gets an answer and is killed after ${n.EXEC_TIMEOUT_MS/1e3}s, so pass the flag that skips the question (\`-y\`, \`--yes\`, \`--no-input\`), and send anything genuinely long to the background with its output redirected to a file.
99
99
 
100
- Keys are not in the environment: every variable named like a key, a token or a secret is removed before the shell starts. An empty one is not an unset one — say which it was, and ask for what a command needs.`;e.s(["createWorkspaceTools",0,(e,n)=>{let u=!0===n.guide,d=async e=>{let t=n.bot;if(!t)return{result:await e(),memory:null};let r=await (0,i.holdBotMemory)(t);return{result:await e(),memory:await (0,i.keepBotMemory)(t,r)}},c=(0,r.tool)({description:"Run a bash command.",inputSchema:o.default.object({command:o.default.string(),description:o.default.string().nullish().describe("One short line for the user: what this command does and why. Shown on their screen while it runs — not a restatement of the command.")}),execute:async({command:t},{abortSignal:r})=>{let{result:o,memory:a}=await d(()=>e.exec(t,{signal:r,env:n.env,timeoutMs:n.timeoutMs})),i=a?{...o,memory:a}:o;return u?(u=!1,{...i,guide:l}):i}});if(!n.write)return{[a.TOOL_NAMES.bash]:c};let p=(0,r.tool)({description:"Write a whole file — what was there is gone. Parent directories are created.",inputSchema:o.default.object({path:o.default.string().describe("Relative to the working directory — under one of its folders — or absolute"),content:o.default.string(),description:o.default.string().nullish().describe("One short line for the user: what this file is. Shown on their screen next to the path.")}),execute:async({path:r,content:o})=>{let a,i=e.resolve(r),l=(0,s.writeRefusal)(i,n.bot);if(l)return l;let{memory:u}=await d(()=>e.writeFile(r,o));return u??`Wrote ${(a=(0,t.relative)(e.cwd,i))&&!a.startsWith("..")?a:i} (${o.split("\n").length} lines)`}});return{[a.TOOL_NAMES.bash]:c,[a.TOOL_NAMES.write_file]:p}}])},75752,e=>{"use strict";var t=e.i(912714),r=e.i(750227),o=e.i(333925),n=e.i(871096);let a=e=>`${(0,n.botFolder)(e)}/memory`;async function i(e,t=o.BOT_MEMORY_LIMITS.files){let l=a(e),u=(0,r.join)(n.WORKSPACE,l),d=(await s(u)).sort((e,t)=>t.info.mtimeMs-e.info.mtimeMs),p=await Promise.all(d.slice(0,t).map(async({name:e,info:t})=>({file:e,path:`${l}/${e}`,line:await c((0,r.join)(u,e)),at:new Date(t.mtimeMs),bytes:t.size})));return{folder:l,entries:p,total:d.length}}async function s(e){let o=await (0,t.readdir)(e).catch(()=>[]);return(await Promise.all(o.filter(e=>!e.startsWith(".")).map(async o=>{let n=await (0,t.stat)((0,r.join)(e,o)).catch(()=>null);return n?.isFile()?{name:o,info:n}:null}))).filter(e=>null!==e)}async function l(e){let i=(0,r.join)(n.WORKSPACE,a(e)),l=new Map;return await Promise.all((await s(i)).map(async({name:e,info:n})=>{let a=n.size>4*o.BOT_MEMORY_LIMITS.chars?null:await (0,t.readFile)((0,r.join)(i,e),"utf8").catch(()=>null);l.set(e,{text:null!==a&&d(a)<=o.BOT_MEMORY_LIMITS.chars?a:null,size:n.size,mtimeMs:n.mtimeMs,atime:n.atime,mtime:n.mtime})})),l}async function u(e,i){let l=a(e),u=(0,r.join)(n.WORKSPACE,l),{files:c,chars:p}=o.BOT_MEMORY_LIMITS,h=[],m=[],g=0;for(let{name:e,info:o}of(await s(u))){g+=1;let n=i.get(e);if(n&&n.size===o.size&&n.mtimeMs===o.mtimeMs)continue;let a=(0,r.join)(u,e),s=d(await (0,t.readFile)(a,"utf8").catch(()=>""));if(s<=p){n||m.push(e);continue}let c=`${s.toLocaleString("en-US")} characters, past the ${p.toLocaleString("en-US")} a memory file holds`;n?null!==n.text?(await (0,t.writeFile)(a,n.text),await (0,t.utimes)(a,n.atime,n.mtime),h.push(`Not kept: \`${l}/${e}\` came to ${c}, so it is back as it was. Write it again shorter.`)):h.push(`\`${l}/${e}\` is ${c}. Shorten it.`):(await (0,t.rm)(a,{force:!0}),g-=1,h.push(`Not kept: \`${l}/${e}\` came to ${c}, so it was removed. Write it again shorter.`))}if(g>c&&m.length){await Promise.all(m.map(e=>(0,t.rm)((0,r.join)(u,e),{force:!0})));let e=m.map(e=>`\`${l}/${e}\``).join(", ");h.push(`Not kept: your memory holds ${c} files at most and this made ${g}, so ${e} ${1===m.length?"was":"were"} removed. Delete or merge files no longer worth keeping, then write it again.`)}return h.length?h.join("\n"):null}let d=e=>[...e.trim()].length;async function c(e){let r=await (0,t.open)(e,"r").catch(()=>null);if(!r)return"";try{let e=Buffer.alloc(1024),{bytesRead:t}=await r.read(e,0,1024,0),o=e.toString("utf8",0,t).split("\n").map(e=>e.trim()).filter(Boolean);if("---"===o[0]){let e=o.find(e=>e.startsWith("description:"));if(e)return e.slice(12).trim().replace(/^["']|["']$/g,"");let t=o.indexOf("---",1);return t>0?(o[t+1]??"").replace(/^#+\s*/,""):""}return(o[0]??"").replace(/^#+\s*/,"")}finally{await r.close()}}e.s(["botMemoryFolder",0,a,"holdBotMemory",0,l,"keepBotMemory",0,u,"listBotMemory",0,i])},277259,e=>e.a(async(t,r)=>{try{var o=e.i(734732),n=e.i(691296),a=e.i(333925),i=e.i(113022),s=e.i(986507),l=e.i(475235),u=e.i(423620),d=e.i(51083),c=e.i(951056),p=e.i(871096),h=e.i(938281),m=e.i(610150),g=e.i(799791),f=e.i(5509),y=t([i,s,l,u,g,f]);[i,s,l,u,g,f]=y.then?(await y)():y;let z=a.BOT_RUN.steps;async function v(e,t){var r,y;let v,w,k,S,T,I,E,C,O,A=t.parent??null,R=await (0,g.findJobBot)(e.bot.trim()),j=R?.name??e.bot.trim(),M=e=>t.emit({...e,bot:j,parent:A});if(!R)return void await M({type:"error",message:`No bot named "${e.bot}". Use a name from the list.`,retry:!1});let N=e.messages,$=await ((r=R).provider&&r.model?(0,s.getTextModel)({provider:r.provider,model:r.model}):(0,s.resolveDefaultModel)().then(s.getTextModel)),P=t.threadId?await (0,f.findThread)(t.threadId):null,[q,{own:L,artifacts:U}]=await Promise.all([t.threadId?(0,p.openJobScratch)(t.threadId,P?.label??"job"):null,(0,p.openBotFolders)(j)]),[D,F]=await Promise.all([(0,l.loadBotPrompt)(j,R.systemPrompt,{thread:t.threadId??null,owner:t.owner,caller:t.caller,messageId:A},{scratch:q,own:L,artifacts:U}),(0,i.loadTools)({target:"bot",bot:j,thread:t.threadId??null,session:t.session??(t.threadId?(0,p.botBrowserSession)(t.threadId,j):null),model:$})]),H=Math.min(await (0,s.compactBudget)($.ref,R.compactAt),t.contextBudget||1/0),B=!1,W={...F,[d.TOOL_NAMES.send_message]:(0,n.tool)({description:u.sendMessageSpec.description,inputSchema:u.sendMessageSpec.parameters,execute:async(e,r)=>{let o=await t.send({...e,id:r.toolCallId});return"question"===e.kind&&(B=!0),o}})},V=new Set,J=(y=a.BOT_RUN.silenceMs,w=new AbortController,k=0,S=!1,T=()=>{clearTimeout(v),v=void 0,S||k>0||(v=setTimeout(()=>{w.abort(new DOMException(`The model sent nothing for ${Math.round(y/6e4)} minutes.`,"TimeoutError"))},y))},{signal:w.signal,touch:T,hold:()=>{k+=1,T()},release:()=>{k=Math.max(0,k-1),T()},end:()=>{S=!0,T()}});for(let[e,r]of Object.entries(W)){let o=r.execute;o&&(r.execute=(r,n)=>{let a=(async()=>{t.signal?.throwIfAborted(),await M({type:"tool",id:n.toolCallId,name:e,input:r}),J.hold();try{t.signal?.throwIfAborted();let a=await o(r,n);if(a&&"object"==typeof a&&Symbol.asyncIterator in a){let e;for await(let t of a)e=t;a=e}return await M({type:"tool-result",id:n.toolCallId,name:e,output:a}),a}catch(t){throw await M({type:"tool-result",id:n.toolCallId,name:e,output:(0,s.modelErrorToString)(t),error:!0}),t}finally{J.release()}})();return V.add(a),a.finally(()=>V.delete(a)).catch(()=>{}),a})}let K=Promise.resolve(),G=()=>{},Y=0,Z=new o.ToolLoopAgent({model:$.model,instructions:D.text,tools:W,stopWhen:[(0,o.stepCountIs)(z),()=>B],prepareStep:async({stepNumber:e,steps:r,messages:o})=>{await K,t.signal?.throwIfAborted();let n={},a=r.at(-1)?.usage.inputTokens??0,i=Math.max(a,o.reduce((e,t)=>e+(0,m.estimateTokens)("string"==typeof t.content?t.content:JSON.stringify(t.content))+4,0));Y=i;let s=o,l=t.compactNow?.()??!1;if((i>H||l)&&o.length>2){J.hold();let e=await _($.model,W,o,{signal:t.signal,budget:H,instructions:D.text}).finally(J.release);h.logger.debug(`compacted ${o.length} messages at ${i} tokens (budget ${H})`);let r=`${e.text}${await b(P?.id??null,o,q)}`;await M({type:"compact",text:r,usage:e.usage,messages:o.length,tokens:i}),s=[o[0],{role:"user",content:r}]}let u=e>0?await t.notes?.()??[]:[];return(u.length&&(s=[...s,...u.map(e=>({role:"user",content:e}))]),s===o)?n:{...n,messages:s}}}),X=(I=[],E=[],C=!1,{push(e){let t=E.shift();t?t(e):I.push(e)},take(){let e=I.shift();return e?Promise.resolve(e):C?Promise.resolve(null):new Promise(e=>E.push(e))},end(){for(let e of(C=!0,E.splice(0)))e(null)}}),Q=t.signal?AbortSignal.any([t.signal,J.signal]):J.signal;J.touch();let ee=new AbortController,et=AbortSignal.any([Q,ee.signal]);try{O=await Z.stream({messages:N,abortSignal:et,onStepEnd:e=>{K=new Promise(e=>{G=e}),X.push({messages:e.response.messages,usage:x(e.usage)})}})}catch(e){throw J.end(),ee.abort(),await Promise.allSettled([...V]),e}let er="",eo="",en=null,ea=e=>{h.logger.error(`${j}: the model run broke`,e);let t=(0,s.modelErrorToString)(e),r=!(0,s.isProviderRefusal)(e);if(!(0,s.isContextOverflow)(e))return{type:"error",message:t,retry:r};let o=Math.floor(Math.min(H,Y||H)*a.BOT_RUN.overflowShrink);return{type:"error",message:t,budget:Math.max(c.COMPACT_AT_MIN,o),retry:r}};Q.addEventListener("abort",()=>{X.end(),G()},{once:!0});try{for await(let e of O.stream)switch(J.touch(),e.type){case"start-step":eo="",er="";break;case"text-delta":er+=e.text;break;case"text-end":{let e=er.trim();if(er="",!e)break;eo=[eo,e].filter(Boolean).join("\n\n"),await M({type:"text",text:e});break}case"tool-call":await M({type:"tool",id:e.toolCallId,name:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:e.providerMetadata});break;case"tool-result":await M({type:"tool-result",id:e.toolCallId,name:e.toolName,output:e.output});break;case"tool-error":await M({type:"tool-result",id:e.toolCallId,name:e.toolName,output:(0,s.modelErrorToString)(e.error),error:!0});break;case"finish-step":{en=e.finishReason;let t=await X.take();t&&await M({type:"step",...t,budget:H}),G();break}case"abort":if(t.signal?.aborted)return;await M(ea(e.reason??"The model stopped sending."));return;case"error":await M(ea(e.error));return}}finally{ee.abort(),X.end(),J.end(),G(),await Promise.allSettled([...V])}try{await O.finalStep}catch(e){if(t.signal?.aborted)return;await M(ea(e));return}"content-filter"===en?await M({type:"error",message:"The provider's content filter stopped the response.",retry:!1}):await M({type:"turn-end",text:eo,stopped:!B&&("length"===en||"error"===en||"tool-calls"===en)})}async function b(e,t,r){try{let o=e?await (0,f.listWrittenPaths)(e):(0,f.writtenPathsIn)(t.map(e=>e.content)),n=await (0,p.filesOnDisk)(o,r);if(!n.length)return"";let i=n.slice(-a.BOT_RUN.compactFiles),s=n.length-i.length,l=i.map(e=>`- ${e}`);return s&&l.unshift(`- …and ${s} older ones`),`
100
+ Keys are not in the environment: every variable named like a key, a token or a secret is removed before the shell starts. An empty one is not an unset one — say which it was, and ask for what a command needs.`;e.s(["createWorkspaceTools",0,(e,n)=>{let u=!0===n.guide,d=async e=>{let t=n.bot;if(!t)return{result:await e(),memory:null};let r=await (0,i.holdBotMemory)(t);return{result:await e(),memory:await (0,i.keepBotMemory)(t,r)}},c=(0,r.tool)({description:"Run a bash command.",inputSchema:o.default.object({command:o.default.string(),description:o.default.string().nullish().describe("One short line for the user: what this command does and why. Shown on their screen while it runs — not a restatement of the command.")}),execute:async({command:t},{abortSignal:r})=>{let{result:o,memory:a}=await d(()=>e.exec(t,{signal:r,env:n.env,timeoutMs:n.timeoutMs})),i=a?{...o,memory:a}:o;return u?(u=!1,{...i,guide:l}):i}});if(!n.write)return{[a.TOOL_NAMES.bash]:c};let p=(0,r.tool)({description:"Write a whole file — what was there is gone. Parent directories are created.",inputSchema:o.default.object({path:o.default.string().describe("Relative to the working directory — under one of its folders — or absolute"),content:o.default.string(),description:o.default.string().nullish().describe("One short line for the user: what this file is. Shown on their screen next to the path.")}),execute:async({path:r,content:o})=>{let a,i=e.resolve(r),l=(0,s.writeRefusal)(i,n.bot);if(l)return l;let{memory:u}=await d(()=>e.writeFile(r,o));return u??`Wrote ${(a=(0,t.relative)(e.cwd,i))&&!a.startsWith("..")?a:i} (${o.split("\n").length} lines)`}});return{[a.TOOL_NAMES.bash]:c,[a.TOOL_NAMES.write_file]:p}}])},75752,e=>{"use strict";var t=e.i(912714),r=e.i(750227),o=e.i(333925),n=e.i(871096);let a=e=>`${(0,n.botFolder)(e)}/memory`;async function i(e,t=o.BOT_MEMORY_LIMITS.files){let l=a(e),u=(0,r.join)(n.WORKSPACE,l),d=(await s(u)).sort((e,t)=>t.info.mtimeMs-e.info.mtimeMs),p=await Promise.all(d.slice(0,t).map(async({name:e,info:t})=>({file:e,path:`${l}/${e}`,line:await c((0,r.join)(u,e)),at:new Date(t.mtimeMs),bytes:t.size})));return{folder:l,entries:p,total:d.length}}async function s(e){let o=await (0,t.readdir)(e).catch(()=>[]);return(await Promise.all(o.filter(e=>!e.startsWith(".")).map(async o=>{let n=await (0,t.stat)((0,r.join)(e,o)).catch(()=>null);return n?.isFile()?{name:o,info:n}:null}))).filter(e=>null!==e)}async function l(e){let i=(0,r.join)(n.WORKSPACE,a(e)),l=new Map;return await Promise.all((await s(i)).map(async({name:e,info:n})=>{let a=n.size>4*o.BOT_MEMORY_LIMITS.chars?null:await (0,t.readFile)((0,r.join)(i,e),"utf8").catch(()=>null);l.set(e,{text:null!==a&&d(a)<=o.BOT_MEMORY_LIMITS.chars?a:null,size:n.size,mtimeMs:n.mtimeMs,atime:n.atime,mtime:n.mtime})})),l}async function u(e,i){let l=a(e),u=(0,r.join)(n.WORKSPACE,l),{files:c,chars:p}=o.BOT_MEMORY_LIMITS,h=[],m=[],g=0;for(let{name:e,info:o}of(await s(u))){g+=1;let n=i.get(e);if(n&&n.size===o.size&&n.mtimeMs===o.mtimeMs)continue;let a=(0,r.join)(u,e),s=d(await (0,t.readFile)(a,"utf8").catch(()=>""));if(s<=p){n||m.push(e);continue}let c=`${s.toLocaleString("en-US")} characters, past the ${p.toLocaleString("en-US")} a memory file holds`;n?null!==n.text?(await (0,t.writeFile)(a,n.text),await (0,t.utimes)(a,n.atime,n.mtime),h.push(`Not kept: \`${l}/${e}\` came to ${c}, so it is back as it was. Write it again shorter.`)):h.push(`\`${l}/${e}\` is ${c}. Shorten it.`):(await (0,t.rm)(a,{force:!0}),g-=1,h.push(`Not kept: \`${l}/${e}\` came to ${c}, so it was removed. Write it again shorter.`))}if(g>c&&m.length){await Promise.all(m.map(e=>(0,t.rm)((0,r.join)(u,e),{force:!0})));let e=m.map(e=>`\`${l}/${e}\``).join(", ");h.push(`Not kept: your memory holds ${c} files at most and this made ${g}, so ${e} ${1===m.length?"was":"were"} removed. Delete or merge files no longer worth keeping, then write it again.`)}return h.length?h.join("\n"):null}let d=e=>[...e.trim()].length;async function c(e){let r=await (0,t.open)(e,"r").catch(()=>null);if(!r)return"";try{let e=Buffer.alloc(1024),{bytesRead:t}=await r.read(e,0,1024,0),o=e.toString("utf8",0,t).split("\n").map(e=>e.trim()).filter(Boolean);if("---"===o[0]){let e=o.find(e=>e.startsWith("description:"));if(e)return e.slice(12).trim().replace(/^["']|["']$/g,"");let t=o.indexOf("---",1);return t>0?(o[t+1]??"").replace(/^#+\s*/,""):""}return(o[0]??"").replace(/^#+\s*/,"")}finally{await r.close()}}e.s(["botMemoryFolder",0,a,"holdBotMemory",0,l,"keepBotMemory",0,u,"listBotMemory",0,i])},277259,e=>e.a(async(t,r)=>{try{var o=e.i(734732),n=e.i(691296),a=e.i(333925),i=e.i(113022),s=e.i(986507),l=e.i(475235),u=e.i(423620),d=e.i(51083),c=e.i(951056),p=e.i(379651),h=e.i(871096),m=e.i(938281),g=e.i(610150),f=e.i(799791),y=e.i(5509),v=t([i,s,l,u,f,y]);[i,s,l,u,f,y]=v.then?(await v)():v;let x=a.BOT_RUN.steps;async function b(e,t){var r,v;let b,z,S,T,I,E,C,O,A,R=t.parent??null,j=await (0,f.findJobBot)(e.bot.trim()),M=j?.name??e.bot.trim(),N=e=>t.emit({...e,bot:M,parent:R});if(!j)return void await N({type:"error",message:`No bot named "${e.bot}". Use a name from the list.`,retry:!1});let $=e.messages,P=await ((r=j).provider&&r.model?(0,s.getTextModel)({provider:r.provider,model:r.model}):(0,s.resolveDefaultModel)().then(s.getTextModel)),q=t.threadId?await (0,y.findThread)(t.threadId):null,[L,{own:U,artifacts:D}]=await Promise.all([t.threadId?(0,h.openJobScratch)(t.threadId,q?.label??"job"):null,(0,h.openBotFolders)(M)]),F=t.session??(t.threadId?(0,h.botBrowserSession)(t.threadId,M):null),[H,B]=await Promise.all([(0,l.loadBotPrompt)(M,j.systemPrompt,{thread:t.threadId??null,owner:t.owner,caller:t.caller,messageId:R},{scratch:L,own:U,artifacts:D}),(0,i.loadTools)({target:"bot",bot:M,thread:t.threadId??null,session:F,model:P})]),W=Math.min(await (0,s.compactBudget)(P.ref,j.compactAt),t.contextBudget||1/0),V=!1,J={...B,[d.TOOL_NAMES.send_message]:(0,n.tool)({description:u.sendMessageSpec.description,inputSchema:u.sendMessageSpec.parameters,execute:async(e,r)=>{let o=await t.send({...e,id:r.toolCallId});return"question"===e.kind&&(V=!0),o}})},K=new Set,G=(v=a.BOT_RUN.silenceMs,z=new AbortController,S=0,T=!1,I=()=>{clearTimeout(b),b=void 0,T||S>0||(b=setTimeout(()=>{z.abort(new DOMException(`The model sent nothing for ${Math.round(v/6e4)} minutes.`,"TimeoutError"))},v))},{signal:z.signal,touch:I,hold:()=>{S+=1,I()},release:()=>{S=Math.max(0,S-1),I()},end:()=>{T=!0,I()}});for(let[e,r]of Object.entries(J)){let o=r.execute;o&&(r.execute=(r,n)=>{let a=(async()=>{t.signal?.throwIfAborted(),await N({type:"tool",id:n.toolCallId,name:e,input:r}),G.hold();try{t.signal?.throwIfAborted();let a=await o(r,n);if(a&&"object"==typeof a&&Symbol.asyncIterator in a){let e;for await(let t of a)e=t;a=e}return await N({type:"tool-result",id:n.toolCallId,name:e,output:a}),a}catch(t){throw await N({type:"tool-result",id:n.toolCallId,name:e,output:(0,s.modelErrorToString)(t),error:!0}),t}finally{G.release()}})();return K.add(a),a.finally(()=>K.delete(a)).catch(()=>{}),a})}let Y=Promise.resolve(),Z=()=>{},X=0,Q=new o.ToolLoopAgent({model:P.model,instructions:H.text,tools:J,stopWhen:[(0,o.stepCountIs)(x),()=>V],prepareStep:async({stepNumber:e,steps:r,messages:o})=>{await Y,t.signal?.throwIfAborted();let n={},a=r.at(-1)?.usage.inputTokens??0,i=Math.max(a,o.reduce((e,t)=>e+(0,g.estimateTokens)("string"==typeof t.content?t.content:JSON.stringify(t.content))+4,0));X=i;let s=o,l=t.compactNow?.()??!1;if((i>W||l)&&o.length>2){G.hold();let e=await w(P.model,J,o,{signal:t.signal,budget:W,instructions:H.text}).finally(G.release);m.logger.debug(`compacted ${o.length} messages at ${i} tokens (budget ${W})`);let r=`${e.text}${await _(q?.id??null,o,L)}`;await N({type:"compact",text:r,usage:e.usage,messages:o.length,tokens:i}),s=[o[0],{role:"user",content:r}]}let u=e>0?await t.notes?.()??[]:[];return(u.length&&(s=[...s,...u.map(e=>({role:"user",content:e}))]),s===o)?n:{...n,messages:s}}}),ee=(E=[],C=[],O=!1,{push(e){let t=C.shift();t?t(e):E.push(e)},take(){let e=E.shift();return e?Promise.resolve(e):O?Promise.resolve(null):new Promise(e=>C.push(e))},end(){for(let e of(O=!0,C.splice(0)))e(null)}}),et=t.signal?AbortSignal.any([t.signal,G.signal]):G.signal;G.touch();let er=new AbortController,eo=AbortSignal.any([et,er.signal]);try{A=await Q.stream({messages:$,abortSignal:eo,onStepEnd:e=>{Y=new Promise(e=>{Z=e}),ee.push({messages:e.response.messages,usage:k(e.usage)})}})}catch(e){throw G.end(),er.abort(),await Promise.allSettled([...K]),e}let en="",ea="",ei=null,es=e=>{m.logger.error(`${M}: the model run broke`,e);let t=(0,s.modelErrorToString)(e),r=!(0,s.isProviderRefusal)(e);if(!(0,s.isContextOverflow)(e))return{type:"error",message:t,retry:r};let o=Math.floor(Math.min(W,X||W)*a.BOT_RUN.overflowShrink);return{type:"error",message:t,budget:Math.max(c.COMPACT_AT_MIN,o),retry:r}};et.addEventListener("abort",()=>{ee.end(),Z()},{once:!0});try{for await(let e of A.stream)switch(G.touch(),e.type){case"start-step":ea="",en="";break;case"text-delta":en+=e.text;break;case"text-end":{let e=en.trim();if(en="",!e)break;ea=[ea,e].filter(Boolean).join("\n\n"),await N({type:"text",text:e});break}case"tool-call":await N({type:"tool",id:e.toolCallId,name:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:e.providerMetadata});break;case"tool-result":await N({type:"tool-result",id:e.toolCallId,name:e.toolName,output:e.output});break;case"tool-error":await N({type:"tool-result",id:e.toolCallId,name:e.toolName,output:(0,s.modelErrorToString)(e.error),error:!0});break;case"finish-step":{ei=e.finishReason;let t=await ee.take();t&&await N({type:"step",...t,budget:W}),Z();break}case"abort":if(t.signal?.aborted)return;await N(es(e.reason??"The model stopped sending."));return;case"error":await N(es(e.error));return}}finally{er.abort(),ee.end(),G.end(),Z(),await Promise.allSettled([...K]),F&&(0,p.renewSignIns)(F).catch(e=>m.logger.warn(`${M}: kept sign-ins were not renewed`,e))}try{await A.finalStep}catch(e){if(t.signal?.aborted)return;await N(es(e));return}"content-filter"===ei?await N({type:"error",message:"The provider's content filter stopped the response.",retry:!1}):await N({type:"turn-end",text:ea,stopped:!V&&("length"===ei||"error"===ei||"tool-calls"===ei)})}async function _(e,t,r){try{let o=e?await (0,y.listWrittenPaths)(e):(0,y.writtenPathsIn)(t.map(e=>e.content)),n=await (0,h.filesOnDisk)(o,r);if(!n.length)return"";let i=n.slice(-a.BOT_RUN.compactFiles),s=n.length-i.length,l=i.map(e=>`- ${e}`);return s&&l.unshift(`- …and ${s} older ones`),`
101
101
 
102
102
  Files this job has on disk now — open one rather than fetching again what is in it:
103
- ${l.join("\n")}`}catch(e){return h.logger.warn("files under the summary could not be listed",e),""}}async function _(e,t,r,n){let a;try{return await w(e,t,r,n)}catch(e){if(n.signal?.aborted)throw e;a=e}if((0,s.isContextOverflow)(a)){let i=(0,o.pruneMessages)({messages:r,toolCalls:"before-last-4-messages",emptyMessages:"remove"});try{return await w(e,t,i,n)}catch(e){if(n.signal?.aborted)throw e;a=e}}throw Error(`Could not compact the context (${(0,s.modelErrorToString)(a)}).`,{cause:a})}async function w(e,t,r,n){let i,{text:s,usage:l}=await (0,o.generateText)({model:e,instructions:n.instructions,tools:t,toolChoice:"none",messages:[...r,{role:"user",content:(i=(e=>{let{min:t,max:r,perTokens:o}=a.BOT_RUN.summaryWords;return Math.min(r,Math.max(t,Math.round(e/o)))})(n.budget),`Compact your context. The first message above — who handed you the job, and the job — stays exactly as it is. Everything after it is replaced by what you write now, and you carry on from that first message and this alone; nothing else above can be read again. Write it for a fresh copy of you that has your tools, your instructions and that first message, but has seen none of the rest.
103
+ ${l.join("\n")}`}catch(e){return m.logger.warn("files under the summary could not be listed",e),""}}async function w(e,t,r,n){let a;try{return await z(e,t,r,n)}catch(e){if(n.signal?.aborted)throw e;a=e}if((0,s.isContextOverflow)(a)){let i=(0,o.pruneMessages)({messages:r,toolCalls:"before-last-4-messages",emptyMessages:"remove"});try{return await z(e,t,i,n)}catch(e){if(n.signal?.aborted)throw e;a=e}}throw Error(`Could not compact the context (${(0,s.modelErrorToString)(a)}).`,{cause:a})}async function z(e,t,r,n){let i,{text:s,usage:l}=await (0,o.generateText)({model:e,instructions:n.instructions,tools:t,toolChoice:"none",messages:[...r,{role:"user",content:(i=(e=>{let{min:t,max:r,perTokens:o}=a.BOT_RUN.summaryWords;return Math.min(r,Math.max(t,Math.round(e/o)))})(n.budget),`Compact your context. The first message above — who handed you the job, and the job — stays exactly as it is. Everything after it is replaced by what you write now, and you carry on from that first message and this alone; nothing else above can be read again. Write it for a fresh copy of you that has your tools, your instructions and that first message, but has seen none of the rest.
104
104
 
105
105
  Cover all of it, and prefer a fact over a description of a fact:
106
106
 
@@ -113,7 +113,7 @@ Cover all of it, and prefer a fact over a description of a fact:
113
113
 
114
114
  Plain text, under ${i} words. No preamble, no headings about the summary itself, no account of how you have been going.`)}],abortSignal:n.signal,timeout:a.BOT_RUN.silenceMs}),u=s.trim();if(!u)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.
115
115
 
116
- ${u}`,usage:x(l)}}let x=e=>({input:e.inputTokens??0,output:e.outputTokens??0});e.s(["resumeTranscript",0,function(e,t=new Map){let r=new Map,o=new Set;for(let t of e)if(("tool"===t.role||"assistant"===t.role)&&Array.isArray(t.content))for(let e of t.content)"tool-result"===e.type&&(r.has(e.toolCallId)||r.set(e.toolCallId,e),"assistant"===t.role&&o.add(e.toolCallId));let n=[],a=new Set;for(let i of e){if("tool"===i.role){let e=i.content.filter(e=>"tool-result"!==e.type);e.length&&n.push({...i,content:e});continue}if("assistant"!==i.role||"string"==typeof i.content){n.push(i);continue}let e=[],s=[];for(let n of i.content){if("tool-call"!==n.type){s.push(n);continue}if(a.has(n.toolCallId))continue;let i=n.input;if("string"==typeof i)try{i=JSON.parse(i)}catch{i=void 0}if(!n.toolCallId||void 0===i){s.push({type:"text",text:"A tool argument stream was interrupted before a complete call was recorded. Inspect the saved work before continuing."});continue}let l=n.toolName===d.TOOL_NAMES.send_message?t.get(n.toolCallId):void 0,u=r.get(n.toolCallId)??(l?{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:{type:"json",value:l}}:void 0);if(n.providerExecuted&&(!u||!o.has(n.toolCallId))){s.push({type:"text",text:u?`The provider operation ${n.toolName} returned this data before its native continuation was interrupted: ${JSON.stringify(u.output)}`:`The provider operation ${n.toolName} was interrupted without a recorded result. Its remote execution state is unknown.`});continue}a.add(n.toolCallId),s.push({...n,input:i}),o.has(n.toolCallId)||e.push(u??{type:"tool-result",toolCallId:n.toolCallId,toolName:n.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."}})}s.length&&n.push({...i,content:s}),e.length&&n.push({role:"tool",content:e})}return n},"runBot",0,v]),r()}catch(e){r(e)}},!1),49002,e=>e.a(async(t,r)=>{try{var o=e.i(136340),n=e.i(232347),a=e.i(333925),i=e.i(986507),s=e.i(475235),l=e.i(520401),u=e.i(375814),d=e.i(871096),c=e.i(528803),p=e.i(938281),h=e.i(212389),m=e.i(991243),g=e.i(64774),f=e.i(799791),y=e.i(277259),v=e.i(951056),b=e.i(811592),_=e.i(600690),w=e.i(5509),z=t([i,s,l,f,y,b,w]);[i,s,l,f,y,b,w]=z.then?(await z)():z;let P=globalThis.__roomRuns??=new Map,q=globalThis.__roomThreadLock??=(0,m.createKeyedLock)(),L=globalThis.__roomPausing??={current:Promise.resolve()},U=globalThis.__roomCompactAsked??=new Set,D=(e,t)=>`${e}
116
+ ${u}`,usage:k(l)}}let k=e=>({input:e.inputTokens??0,output:e.outputTokens??0});e.s(["resumeTranscript",0,function(e,t=new Map){let r=new Map,o=new Set;for(let t of e)if(("tool"===t.role||"assistant"===t.role)&&Array.isArray(t.content))for(let e of t.content)"tool-result"===e.type&&(r.has(e.toolCallId)||r.set(e.toolCallId,e),"assistant"===t.role&&o.add(e.toolCallId));let n=[],a=new Set;for(let i of e){if("tool"===i.role){let e=i.content.filter(e=>"tool-result"!==e.type);e.length&&n.push({...i,content:e});continue}if("assistant"!==i.role||"string"==typeof i.content){n.push(i);continue}let e=[],s=[];for(let n of i.content){if("tool-call"!==n.type){s.push(n);continue}if(a.has(n.toolCallId))continue;let i=n.input;if("string"==typeof i)try{i=JSON.parse(i)}catch{i=void 0}if(!n.toolCallId||void 0===i){s.push({type:"text",text:"A tool argument stream was interrupted before a complete call was recorded. Inspect the saved work before continuing."});continue}let l=n.toolName===d.TOOL_NAMES.send_message?t.get(n.toolCallId):void 0,u=r.get(n.toolCallId)??(l?{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:{type:"json",value:l}}:void 0);if(n.providerExecuted&&(!u||!o.has(n.toolCallId))){s.push({type:"text",text:u?`The provider operation ${n.toolName} returned this data before its native continuation was interrupted: ${JSON.stringify(u.output)}`:`The provider operation ${n.toolName} was interrupted without a recorded result. Its remote execution state is unknown.`});continue}a.add(n.toolCallId),s.push({...n,input:i}),o.has(n.toolCallId)||e.push(u??{type:"tool-result",toolCallId:n.toolCallId,toolName:n.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."}})}s.length&&n.push({...i,content:s}),e.length&&n.push({role:"tool",content:e})}return n},"runBot",0,b]),r()}catch(e){r(e)}},!1),49002,e=>e.a(async(t,r)=>{try{var o=e.i(136340),n=e.i(232347),a=e.i(333925),i=e.i(986507),s=e.i(475235),l=e.i(520401),u=e.i(375814),d=e.i(871096),c=e.i(528803),p=e.i(938281),h=e.i(212389),m=e.i(991243),g=e.i(64774),f=e.i(799791),y=e.i(277259),v=e.i(951056),b=e.i(811592),_=e.i(600690),w=e.i(5509),z=t([i,s,l,f,y,b,w]);[i,s,l,f,y,b,w]=z.then?(await z)():z;let P=globalThis.__roomRuns??=new Map,q=globalThis.__roomThreadLock??=(0,m.createKeyedLock)(),L=globalThis.__roomPausing??={current:Promise.resolve()},U=globalThis.__roomCompactAsked??=new Set,D=(e,t)=>`${e}
117
117
  ${t}`;async function x(e){let t=await (0,f.findJobBot)(e.bot);(!t||t.disabled)&&(0,h.publicError)("Choose an enabled bot.");let{from:r,routine:o,...n}={...e,bot:t.name},a=(0,s.buildThreadOpening)({bot:n.bot,request:n.request,from:r,routine:o}),i=await (0,w.insertThread)({...n,routineId:o?.id??null,opening:a});return await S(i.id),i.id}async function k(e,t,r="user",o,n){let a=null;return await q(e,async()=>{let i=await (0,w.findThread)(e);if(i||(0,h.publicError)("No such thread."),o){let t=(await (0,b.listRoomWork)(e)).find(e=>e.bot.toLowerCase()===o.trim().toLowerCase());t&&t.bot!==_.ROOM_THURSDAY||(0,h.publicError)("Choose a participant in this thread."),o=t.bot}t.trim()===v.THREAD_CONTINUE&&(0,v.isAppStop)(i.pending)?(await (0,b.resumeRoom)(e),(await (0,b.listRoomWork)(e)).some(e=>"queued"===e.state)||(a=await (0,b.tellRoom)(e,"Continue from the saved conversation.","user"===r?"The user":_.ROOM_THURSDAY,o,void 0,!1))):a=await (0,b.tellRoom)(e,t,"user"===r?"The user":_.ROOM_THURSDAY,o,n)}),await S(e),a}async function S(e){await q(e,async()=>{if(!n.presence.watching&&!await (0,f.readKeepWorkingOn)()){let t=await (0,w.findThread)(e);t?.status!=="running"||[...P.values()].some(t=>t.threadId===e)||await (0,b.pauseRoom)(e,"The app is not open. Work resumes when it returns.",!0);return}for(let t=0;t<2;t++){let t;for(;t=await (0,b.claimRoomWork)(e);)!function(e){let t,r=new AbortController,o=new Promise(e=>{t=e});P.set(e.id,{threadId:e.threadId,stop:r,done:o}),T(e,r.signal).catch(t=>p.logger.error(`thread ${e.threadId}: participant`,t)).finally(()=>{P.delete(e.id),t(),S(e.threadId).catch(t=>p.logger.error(`thread ${e.threadId}: scheduling`,t))})}(t);await (0,b.settleRoom)(e)}})}async function T(e,t){let r=await I(e,t);if(r?.failure?.retry&&!t.aborted&&(await (0,b.noteRoomBreak)(e,r.failure.message),await (0,o.setTimeout)(a.BOT_RUN.retryMs,void 0,{signal:t}).catch(()=>{}),t.aborted||(r=await I(e,t))),!r||t.aborted)return;let i=r.failure?.message,s=r.ending;if(i||!s||s.stopped){let t=i??"The turn was interrupted. Continue from the saved conversation.";q(e.threadId,async()=>{let r=(await (0,b.listRoomWork)(e.threadId)).find(t=>t.id===e.id);if(r?.state!=="running"||r.generation!==e.generation)return;let o=E(e.threadId);await (0,b.pauseRoom)(e.threadId,t),await o}).catch(t=>p.logger.error(`thread ${e.threadId}: pausing`,t));return}await (0,b.finishRoomWork)(e,s.text);let h=await (0,w.findThread)(e.threadId);if(h?.status==="done"){n.presence.watching||await (0,l.isAnyCallLive)()||(0,c.desktopNotify)(h.label,h.outcome??"");let e=await (0,d.filesOnDisk)((0,u.pathsIn)(h.outcome??""),null),t=e.findIndex(u.opensOnFinish);n.appEvents.emit({type:"finished",threadId:h.id,label:h.label,bot:h.bot,words:(0,g.plainText)(h.outcome??"").slice(0,a.FINISHED_NOTICE.words),paths:t>0?[e[t],...e.filter((e,r)=>r!==t)]:e})}}async function I(e,t){let r=new F(e,t),o=null,n=null;try{let a=await (0,w.findThread)(e.threadId);if(!a)return null;(await (0,b.listParticipantTranscript)(e.threadId,e.bot)).length||await (0,b.appendRoomMessage)(e.threadId,{bot:e.bot,parent:e.id,role:"user",content:`Request: ${a.request}
118
118
  Coordinator: ${a.bot}. Continue as ${e.bot} in this thread.`,hidden:!0}),await (0,b.consumeRoomInbox)(e);let i=await (0,b.listParticipantTranscript)(e.threadId,e.bot);await (0,y.runBot)({bot:e.bot,messages:(0,y.resumeTranscript)(i,await (0,b.listRoomReceipts)(e.threadId,e.bot,i))},{signal:t,threadId:e.threadId,parent:e.id,caller:e.caller,owner:a.bot,contextBudget:await (0,b.roomContextBudget)(e.threadId,e.bot),compactNow:()=>U.delete(D(e.threadId,e.bot)),session:(0,d.botBrowserSession)(e.threadId,e.bot),notes:()=>(0,b.consumeRoomInbox)(e),send:async r=>{t.throwIfAborted();let o=r.to.trim();if(o.toLowerCase()===_.ROOM_THURSDAY.toLowerCase())o=_.ROOM_THURSDAY;else{let e=await (0,f.findJobBot)(o);(!e||e.disabled)&&(0,h.publicError)(`No enabled bot named "${o}".`),o=e.name}let n=await (0,b.sendRoomMessage)(e,{...r,to:o});return S(e.threadId).catch(e=>p.logger.error("room message scheduling",e)),n},emit:async i=>{(!t.aborted||"tool-result"===i.type)&&(await r.on(i),"step"===i.type&&await (0,w.addThreadUsage)(e.threadId,i.usage,e.bot===a.bot?{tokens:i.usage.input,budget:i.budget}:null),"compact"===i.type&&await (0,w.addThreadUsage)(e.threadId,i.usage),"turn-end"===i.type&&(o=i),"error"===i.type&&(n={message:i.message,retry:i.retry},i.budget&&await (0,b.lowerRoomContextBudget)(e,i.budget)))}})}catch(r){t.aborted||(p.logger.error(`thread ${e.threadId}: ${e.bot} broke`,r),n={message:(0,i.modelErrorToString)(r),retry:!(0,h.isPublicError)(r)&&!(0,i.isProviderRefusal)(r)})}return{ending:o,failure:n}}class F{work;signal;lane;assistant;tool;parts;calls;results;constructor(e,t){this.work=e,this.signal=t,this.lane=(0,g.PromiseChain)(),this.assistant=null,this.tool=null,this.parts={assistant:[],tool:[]},this.calls=new Set,this.results=new Set}async write(e,t,r=!1){let o={bot:this.work.bot,parent:this.work.id,role:t.role,content:t.content,compact:r,note:r};return null===e?(0,b.appendRoomMessage)(this.work.threadId,o):(await (0,w.upsertMessage)(this.work.threadId,e,o),e)}on(e){return this.lane(async()=>{if(!this.signal.aborted||"tool-result"===e.type)if("text"===e.type)this.parts.assistant.push({type:"text",text:e.text}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant});else if("tool"===e.type){if(this.calls.has(e.id)){let t=this.parts.assistant.find(t=>"tool-call"===t.type&&t.toolCallId===e.id);t&&"tool-call"===t.type&&e.providerOptions&&(t.providerOptions=e.providerOptions,this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant}));return}this.calls.add(e.id),this.parts.assistant.push({type:"tool-call",toolCallId:e.id,toolName:e.name,input:e.input,...e.providerExecuted?{providerExecuted:!0}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{}}),this.assistant=await this.write(this.assistant,{role:"assistant",content:this.parts.assistant})}else if("tool-result"===e.type){if(this.results.has(e.id))return;this.results.add(e.id),this.parts.tool.push({type:"tool-result",toolCallId:e.id,toolName:e.name,output:e.error?{type:"error-text",value:String(e.output)}:"string"==typeof e.output?{type:"text",value:e.output}:{type:"json",value:e.output}}),this.tool=await this.write(this.tool,{role:"tool",content:this.parts.tool})}else if("step"===e.type){let t=[this.assistant,this.tool];for(let[r,o]of e.messages.entries())await this.write(t[r]??null,o);let r=t.slice(e.messages.length).filter(e=>null!==e);r.length&&await (0,w.deleteMessages)(this.work.threadId,r),this.assistant=this.tool=null,this.parts={assistant:[],tool:[]}}else"compact"===e.type&&await this.write(null,{role:"user",content:e.text},!0)})}}async function E(e){let t=[...P.values()].filter(t=>t.threadId===e);for(let e of t)e.stop.abort();await Promise.all(t.map(e=>e.done))}async function C(e){await q(e,async()=>{let t=await (0,w.findThread)(e);t||(0,h.publicError)("No such thread."),t.endedAt&&(0,h.publicError)("That thread has already ended."),await (0,b.cancelRoom)(e),await (0,w.updateThread)(e,{status:"cancelled",outcome:null,pending:null,seen:!0,endedAt:new Date}),await E(e),await (0,d.closeJobShell)(e)})}async function O(e){return q(e,()=>A(e))}async function A(e){let t=await (0,w.findThread)(e);await (0,b.cancelRoom)(e),await E(e),await (0,d.removeJobBrowsers)(e);let r=await (0,w.deleteThread)(e);return r&&t&&await (0,d.removeJobScratch)(e,t.label),r}async function R(){let e=0;for(let t of(await (0,w.listThreadFolders)()))("done"===t.status||"cancelled"===t.status)&&await q(t.id,async()=>{let r=await (0,w.findThread)(t.id);(r?.status==="done"||r?.status==="cancelled")&&await A(t.id)&&(e+=1)});return e}async function j(){let e=Date.now()-a.WORKSPACE_KEEP.forMs,t=t=>("done"===t.status||"cancelled"===t.status)&&(t.endedAt??t.updatedAt).getTime()<e,r=new Set(await (0,d.listScratchFolders)()),o=[];for(let e of(await (0,w.listThreadFolders)())){let n=(0,d.jobScratch)(e.id,e.label);r.delete(n)&&t(e)&&await q(e.id,async()=>{let r=await (0,w.findThread)(e.id);r&&t(r)&&(await (0,d.closeHiddenBrowser)(e.id),await (0,d.removeJobScratch)(e.id,e.label),o.push(n))})}return o.push(...await (0,d.removeUnchangedFolders)([...r])),await (0,d.pruneJobFiles)(),o.length&&p.logger.info(`cleared ${o.length} old job folder(s): ${o.join(", ")}`),o}async function M(){for(let e of(await (0,w.listRunningThreadIds)()))await q(e,async()=>{[...P.values()].some(t=>t.threadId===e)||(await (0,w.findThread)(e))?.status==="running"&&await (0,b.pauseRoom)(e,"The server restarted. Resume from the saved conversation.")})}async function N(e,t=!1){let r=(async()=>{let r=await (0,w.listRunningThreadIds)();await Promise.all(r.map(r=>q(r,async()=>{(await (0,w.findThread)(r))?.status==="running"&&(await E(r),await (0,b.pauseRoom)(r,e,t))})))})();L.current=r,await r}async function $(){if(await L.current,n.presence.watching)for(let e of(await (0,w.listAutoStoppedThreads)()))await q(e,async()=>{let t=await (0,w.findThread)(e);t?.status==="waiting"&&t.pending?.auto&&await (0,b.resumeRoom)(e,!1)}),await S(e)}e.s(["answerThread",0,k,"askCompact",0,function(e,t){U.add(D(e,t))},"cancelThread",0,C,"pauseThreads",0,N,"removeFinishedThreads",0,R,"removeThread",0,O,"resumeStoppedThreads",0,$,"startThread",0,x,"sweepJobFiles",0,j,"sweepThreads",0,M]),r()}catch(e){r(e)}},!1),811592,e=>e.a(async(t,r)=>{try{var o=e.i(666680),n=e.i(336763),a=e.i(157406),i=e.i(533102),s=e.i(232347),l=e.i(333925),u=e.i(876393),d=e.i(220376),c=e.i(51083),p=e.i(212389),h=e.i(951056),m=e.i(600690),g=t([u]);[u]=g.then?(await g)():g;let L=()=>s.appEvents.emit({type:"threads"}),U=e=>"done"===e||"cancelled"===e,D=(e,t,r)=>`message:${(0,o.createHash)("sha256").update(JSON.stringify([e,t,r])).digest("hex")}`;async function f(e,t,r){let[o]=await e.select({id:d.threadWorkTable.id}).from(d.threadWorkTable).where((0,n.and)((0,n.eq)(d.threadWorkTable.threadId,t),(0,n.eq)(d.threadWorkTable.state,"external"),(0,n.eq)(d.threadWorkTable.caller,r))).limit(1);return!!o}async function y(e,t,r){let o=r.flatMap(e=>"assistant"===e.role&&Array.isArray(e.content)?e.content.flatMap(e=>"tool-call"===e.type&&e.toolName===c.TOOL_NAMES.send_message?[e.toolCallId]:[]):[]),a=o.map(r=>D(e,t,r)),i=new Map;if(!a.length)return i;let[s,l]=await Promise.all([u.database.select({key:d.threadWorkTable.id,to:d.threadWorkTable.bot}).from(d.threadWorkTable).where((0,n.and)((0,n.eq)(d.threadWorkTable.threadId,e),(0,n.inArray)(d.threadWorkTable.id,a))),u.database.select({key:d.threadDeliveryTable.key,to:d.threadWorkTable.bot}).from(d.threadDeliveryTable).innerJoin(d.threadWorkTable,(0,n.eq)(d.threadWorkTable.id,d.threadDeliveryTable.workId)).where((0,n.and)((0,n.eq)(d.threadDeliveryTable.threadId,e),(0,n.inArray)(d.threadDeliveryTable.key,a)))]),p=new Map([...s,...l].map(e=>[e.key,e.to]));for(let[e,t]of o.entries()){let r=p.get(a[e]);r&&i.set(t,{messageId:a[e],to:r})}return i}async function v(e,t,r){let[o]=await e.select({seq:(0,a.max)(d.threadMessageTable.seq)}).from(d.threadMessageTable).where((0,n.eq)(d.threadMessageTable.threadId,t)),i=(o?.seq??-1)+1;return await e.insert(d.threadMessageTable).values({threadId:t,seq:i,...r}),i}let F=(e,t)=>({bot:e.bot,parent:e.id,role:"user",content:`${t} ${m.RESUME_CHECK}`,note:!0});async function b(e,t){await _(e.threadId,F(e,t))}async function _(e,t){let r=await u.database.transaction(r=>v(r,e,t));return L(),r}async function w(e){return u.database.select().from(d.threadWorkTable).where((0,n.eq)(d.threadWorkTable.threadId,e)).orderBy(d.threadWorkTable.createdAt,d.threadWorkTable.id)}async function z(e,t){let[r]=await u.database.select({budget:i.sql`min(nullif(${d.threadWorkTable.contextBudget}, 0))`}).from(d.threadWorkTable).where((0,n.and)((0,n.eq)(d.threadWorkTable.threadId,e),(0,n.eq)(d.threadWorkTable.bot,t)));return r?.budget??void 0}async function x(e,t){await u.database.transaction(async r=>{await k(r,e),await r.update(d.threadWorkTable).set({contextBudget:t}).where((0,n.eq)(d.threadWorkTable.id,e.id))}),L()}async function k(e,t){let[r]=await e.select().from(d.threadWorkTable).where((0,n.and)((0,n.eq)(d.threadWorkTable.id,t.id),(0,n.eq)(d.threadWorkTable.generation,t.generation),(0,n.eq)(d.threadWorkTable.state,"running")));return r||(0,p.publicError)("This turn is no longer running."),r}async function S(e,t){await e.insert(d.threadDeliveryTable).values(t).onConflictDoNothing();let[r]=await e.select({bot:d.threadWorkTable.bot}).from(d.threadWorkTable).where((0,n.eq)(d.threadWorkTable.id,t.workId));r&&await f(e,t.threadId,r.bot)||await e.update(d.threadWorkTable).set({state:"queued"}).where((0,n.and)((0,n.eq)(d.threadWorkTable.id,t.workId),(0,n.inArray)(d.threadWorkTable.state,["waiting","done"])))}async function T(e,t){let r={...m.RoomMessageSchema.parse(t),id:t.id};"question"===r.kind&&r.to!==m.ROOM_THURSDAY&&(0,p.publicError)("Address user questions to Thursday; use a message to contact another bot."),r.options?.length&&"question"!==r.kind&&(0,p.publicError)("Offer answer choices only with a user question.");let o=await u.database.transaction(async t=>{await k(t,e);let o=D(e.threadId,e.bot,r.id),[a]=await t.select().from(d.threadWorkTable).where((0,n.eq)(d.threadWorkTable.id,o));if(a)return{messageId:o,to:a.bot};let[i]=await t.select({to:d.threadWorkTable.bot}).from(d.threadDeliveryTable).innerJoin(d.threadWorkTable,(0,n.eq)(d.threadWorkTable.id,d.threadDeliveryTable.workId)).where((0,n.eq)(d.threadDeliveryTable.key,o));if(i)return{messageId:o,to:i.to};if(r.to===e.bot&&(0,p.publicError)("Continue your own work directly; choose another recipient."),r.replyTo){let[a]=await t.select().from(d.threadWorkTable).where((0,n.and)((0,n.eq)(d.threadWorkTable.id,r.replyTo),(0,n.eq)(d.threadWorkTable.threadId,e.threadId)));if((!a||a.bot!==e.bot||a.caller!==r.to||U(a.state))&&(0,p.publicError)("Reply to an open message addressed to you from that recipient."),a.parentId)return await S(t,{key:o,threadId:e.threadId,workId:a.parentId,speaker:e.bot,text:r.text}),{messageId:o,to:r.to}}let s=await t.select().from(d.threadWorkTable).where((0,n.eq)(d.threadWorkTable.threadId,e.threadId)),u=new Set(s.map(e=>e.bot).filter(e=>e!==m.ROOM_THURSDAY));r.to!==m.ROOM_THURSDAY&&!u.has(r.to)&&u.size>=l.BOT_RUN.participants&&(0,p.publicError)("This thread has reached its participant limit."),s.filter(e=>!U(e.state)).length>=l.BOT_RUN.queuedMessages&&(0,p.publicError)("This thread has reached its pending message limit.");let c=r.to!==m.ROOM_THURSDAY&&await f(t,e.threadId,r.to);return await t.insert(d.threadWorkTable).values({id:o,threadId:e.threadId,bot:r.to,caller:e.bot,parentId:e.id,state:r.to===m.ROOM_THURSDAY?"question"===r.kind?"external":"done":c?"waiting":"queued",result:r.to===m.ROOM_THURSDAY?r.text:null,options:[...new Set(r.options??[])]}),r.to===m.ROOM_THURSDAY?await t.insert(d.threadRelayTable).values({key:o,threadId:e.threadId,bot:e.bot,text:r.text,kind:r.kind,messageId:"question"===r.kind?o:null}):await S(t,{key:o,threadId:e.threadId,workId:o,speaker:e.bot,text:r.text}),await t.update(d.threadTable).set({wrapped:!1,updatedAt:new Date}).where((0,n.eq)(d.threadTable.id,e.threadId)),{messageId:o,to:r.to,...c?{note:`${r.to} is waiting for the user's answer and reads this after it.`}:{}}});return L(),o}async function I(e){let t=!1,r=await u.database.transaction(async r=>{let[o]=await r.select().from(d.threadTable).where((0,n.eq)(d.threadTable.id,e));if(!o||"running"!==o.status)return null;let a=await r.select().from(d.threadWorkTable).where((0,n.eq)(d.threadWorkTable.threadId,e)).orderBy(i.sql`${d.threadWorkTable}.rowid`),s=new Set(a.filter(e=>"external"===e.state).map(e=>e.caller));for(let e of a)"queued"===e.state&&s.has(e.bot)&&(await r.update(d.threadWorkTable).set({state:"waiting"}).where((0,n.eq)(d.threadWorkTable.id,e.id)),e.state="waiting",t=!0);let u=a.filter(e=>"running"===e.state);if(u.length>=l.BOT_RUN.concurrent)return null;let c=a.find(e=>"queued"===e.state&&!u.some(t=>t.bot===e.bot));if(!c)return null;if(o.turns>=l.BOT_RUN.turns)return await r.update(d.threadWorkTable).set({state:"paused"}).where((0,n.and)((0,n.eq)(d.threadWorkTable.threadId,e),(0,n.eq)(d.threadWorkTable.state,"queued"))),null;let[p]=await r.update(d.threadWorkTable).set({state:"running",generation:c.generation+1}).where((0,n.eq)(d.threadWorkTable.id,c.id)).returning();return await r.update(d.threadTable).set({turns:o.turns+1}).where((0,n.eq)(d.threadTable.id,e)),p});return(r||t)&&L(),r}async function E(e){let t=await u.database.transaction(async t=>{await k(t,e);let r=await t.select().from(d.threadDeliveryTable).where((0,n.and)((0,n.eq)(d.threadDeliveryTable.workId,e.id),(0,n.eq)(d.threadDeliveryTable.consumed,!1))).orderBy(d.threadDeliveryTable.id);for(let o of r){let r=C(o);await v(t,e.threadId,{bot:e.bot,parent:e.id,role:"user",content:r,hidden:!o.visible}),await t.update(d.threadDeliveryTable).set({consumed:!0}).where((0,n.eq)(d.threadDeliveryTable.id,o.id))}return r.map(C)});return t.length&&L(),t}function C(e){return e.visible?(0,h.tagSpeaker)("The user"===e.speaker?"user":"thursday",e.text):`${e.speaker}:
119
119
 
@@ -1,4 +1,4 @@
1
- module.exports=[56802,e=>e.a(async(t,a)=>{try{e.i(687388);var o=e.i(378884);e.i(704161);var n=t([o]);[o]=n.then?(await n)():n,e.s([]),a()}catch(e){a(e)}},!1),962072,e=>e.a(async(t,a)=>{try{var o=e.i(687388),n=e.i(186304),s=e.i(353885),r=e.i(265143),i=e.i(378884),h=e.i(619898),l=e.i(453569),d=e.i(636882),u=e.i(22676),c=e.i(786025),m=e.i(660948),w=e.i(54282),y=t([r,i,h,u,m]);async function p(e,t=!1){var a,y,f,b,k,v,O;let T,E=await (0,c.openWorkspace)(),[S,$,A,_,M,L,N,C,I]=await Promise.all([(0,d.loadSkills)(E),(0,h.listNoteIndex)(),(0,h.listAlwaysLoaded)(),(0,h.readNotes)(l.MEMORY_ALWAYS_LISTED,{touch:!1}),(0,m.listConnectedToolNames)(),(0,r.listJobBots)(),(0,u.listRecentTurns)(o.RECENT_CALL.rows),(0,u.readCallSkillsOn)(),(0,r.readBotMemoryOn)()]),x=await (0,i.listCallJobs)(N.map(e=>e.callId)),j=[(0,w.thursdayIdentity)(),t?"":(0,w.callEnding)(),function(e,t,a){let{crowded:o,heavy:n}=(0,w.tidying)(e),r=[...n].sort((e,t)=>t.factCount-e.factCount).slice(0,3).map(e=>e.path),i=o||n.length?`
1
+ module.exports=[56802,e=>e.a(async(t,a)=>{try{e.i(687388);var o=e.i(378884);e.i(704161);var n=t([o]);[o]=n.then?(await n)():n,e.s([]),a()}catch(e){a(e)}},!1),962072,e=>e.a(async(t,a)=>{try{var o=e.i(687388),n=e.i(186304),s=e.i(353885),r=e.i(265143),i=e.i(378884),h=e.i(619898),l=e.i(453569),d=e.i(636882),u=e.i(22676),c=e.i(786025),m=e.i(660948),w=e.i(54282),y=t([r,i,h,u,m]);async function g(e,t=!1){var a,y,b,k,v,O,T;let S,E=await (0,c.openWorkspace)(),[$,A,_,M,L,N,C,I,x]=await Promise.all([(0,d.loadSkills)(E),(0,h.listNoteIndex)(),(0,h.listAlwaysLoaded)(),(0,h.readNotes)(l.MEMORY_ALWAYS_LISTED,{touch:!1}),(0,m.listConnectedToolNames)(),(0,r.listJobBots)(),(0,u.listRecentTurns)(o.RECENT_CALL.rows),(0,u.readCallSkillsOn)(),(0,r.readBotMemoryOn)()]),j=await (0,i.listCallJobs)(C.map(e=>e.callId)),q=[(0,w.thursdayIdentity)(),t?"":p(),function(e,t,a){let{crowded:o,heavy:n}=(0,w.tidying)(e),r=[...n].sort((e,t)=>t.factCount-e.factCount).slice(0,3).map(e=>e.path),i=o||n.length?`
2
2
 
3
3
  Saved memory has grown past what it holds well${r.length?` (${r.join(", ")})`:""}: say so once in what you return, go through what looks out of date with the user, and forget only what they name.`:"",h=new Set(a.map(e=>e.path)),d=new Set(t.map(e=>e.id)),u=`## Memory
4
4
 
@@ -7,7 +7,7 @@ What you have kept from talking with this user — the only thing that survives
7
7
  ${a.map(e=>(function(e,t){let{shown:a,hidden:o}=(0,w.expandedFacts)(e.facts,t),n=a.map(e=>`- ${e.text} #${e.id}`);return o&&n.push(`- … ${o} older not shown — \`${s.TOOL_NAMES.memory_recall}\` ${e.path} opens the whole note`),`${e.path} — ${e.description}
8
8
  ${n.length?n.join("\n"):"- (nothing yet)"}`})(e,d)).join("\n\n")}`,m=t.filter(e=>!h.has(e.path)),y=m.length?`Already known — carried into every call:
9
9
 
10
- ${(0,w.carriedLines)(m)}`:"",p=`Every other note — path — what is under it (facts) "what the user calls it":
10
+ ${(0,w.carriedLines)(m)}`:"",g=`Every other note — path — what is under it (facts) "what the user calls it":
11
11
 
12
12
  ${(0,w.noteLines)(e.filter(e=>!h.has(e.path)),o)}${i}
13
13
 
@@ -17,7 +17,7 @@ Keep what the user tells you as it comes up, with \`${s.TOOL_NAMES.memory_rememb
17
17
 
18
18
  **Keep memory clean as you write.** A fact that repeats, narrows or changes one already in the note replaces it, merged into one line, rather than sitting beside it. A later call finds a note only by its path, its line and the names in quotes: keep the line true, and give something new its own path below.
19
19
 
20
- ${l.MEMORY_PATHS.map(e=>`- ${e.path} — ${e.of}`).join("\n")}`;return[u,c,y,p].filter(Boolean).join("\n\n")}($,A,_.notes),(a=L,y=(0,w.reachNames)(C?[]:S,M),f=I,0===a.length?"":`## Background work
20
+ ${l.MEMORY_PATHS.map(e=>`- ${e.path} — ${e.of}`).join("\n")}`;return[u,c,y,g].filter(Boolean).join("\n\n")}(A,_,M.notes),(a=N,y=(0,w.reachNames)(I?[]:$,L),b=x,0===a.length?"":`## Background work
21
21
 
22
22
  Who you hand work to — the names \`${s.TOOL_NAMES.thread_start}\` takes.
23
23
 
@@ -25,37 +25,37 @@ ${a.map(e=>`- **${e.name}** — ${e.description}`).join("\n")}${y?`
25
25
 
26
26
  What bots can reach for: ${y}.`:""}
27
27
 
28
- **A bot can take on almost anything, and anything that takes more than a few seconds is a bot's**; a note, a look at a file or one command is yours. A bot has this computer, a real browser, the web, a shell to build what is missing and far more time than a call; it signs in where it has to and carries work to the end, so something you do not know how to do is work for a bot, not a no. Bots bring each other in, so work that spans several things is still one thread.${f?" Each bot keeps its own memory from thread to thread: when the user says how a bot should work from now on, pass it to that bot to remember.":""}
28
+ **A bot can take on almost anything, and anything that takes more than a few seconds is a bot's**; a note, a look at a file or one command is yours. A bot has this computer, a real browser, the web, a shell to build what is missing and far more time than a call; it signs in where it has to and carries work to the end, so something you do not know how to do is work for a bot, not a no. Bots bring each other in, so work that spans several things is still one thread.${b?" Each bot keeps its own memory from thread to thread: when the user says how a bot should work from now on, pass it to that bot to remember.":""}
29
29
 
30
30
  **Work lives in threads.** A thread's bot remembers that thread and nothing else, so the same bot started on a new one begins from nothing. More about work already handed over — a correction, the next step once it finished, going on after it stopped — is said to that thread (\`${s.TOOL_NAMES.thread_tell}\`); only a request that stands on its own starts a new one (\`${s.TOOL_NAMES.thread_start}\`). The threads open as this call started come into the conversation at the start, and they move while you talk: \`${s.TOOL_NAMES.thread_status}\` reads them as they are now, before you answer about one or hand anything over. Ask the user which it is only when the request could be either. Write the request in the user's own words, with what it stands on — including how they told you they want work done — and nothing they did not say.
31
31
 
32
32
  **Work that should start by itself — every morning, every few hours — is a routine.** \`${s.TOOL_NAMES.routine}\` makes one from a bot, the work in the user's own words, and when; from then on it starts a thread for it each time without being asked, and the result reaches the user like any thread's. Ask once for whichever of those they left out, and read the ones that exist before making, changing or deleting one.
33
33
 
34
- Updates and questions from threads reach the conversation by themselves, naming their thread and the bot that asks; they come from bots, not the user, and a question is answered with \`${s.TOOL_NAMES.thread_answer}\`. When the user wants to see what a thread made, \`${s.TOOL_NAMES.thread_show}\` puts it on their screen. Once you have explained enough of how a thread ended, mark it with \`${s.TOOL_NAMES.thread_seen}\`, or leave it for the user to open; never mention seen to them.`),(b=E.cwd,k=C?S:[],T=`## This computer
34
+ Updates and questions from threads reach the conversation by themselves, naming their thread and the bot that asks; they come from bots, not the user, and a question is answered with \`${s.TOOL_NAMES.thread_answer}\`. When the user wants to see what a thread made, \`${s.TOOL_NAMES.thread_show}\` puts it on their screen. Once you have explained enough of how a thread ended, mark it with \`${s.TOOL_NAMES.thread_seen}\`, or leave it for the user to open; never mention seen to them.`),(k=E.cwd,v=I?$:[],S=`## This computer
35
35
 
36
- Current Cwd: ${b}
36
+ Current Cwd: ${k}
37
37
  Platform: ${process.platform}
38
38
 
39
39
  Where \`${s.TOOL_NAMES.bash}\` runs, and what the paths you get back are relative to. Each command is cut off after ${Math.round(o.CALL_EXEC_TIMEOUT_MS/1e3)} seconds; anything longer is a bot's.
40
40
 
41
- ${(0,n.guideLine)()}`,0===k.length?T:`${T}
41
+ ${(0,n.guideLine)()}`,0===v.length?S:`${S}
42
42
 
43
43
  Skills are written-down ways of doing things here. \`${s.TOOL_NAMES.load_skill}\` opens one, and what it says goes for you too: read one when it covers what was asked and the doing is a glance. Anything longer it describes is still work to hand over, with what the skill said.
44
44
 
45
- ${(0,w.skillLines)(k,{short:!0})}`),t?`## Answer in writing
45
+ ${(0,w.skillLines)(v,{short:!0})}`),t?`## Answer in writing
46
46
 
47
47
  This call is in writing: there is no voice, and what you write is what the user reads, so answer them directly, in their language. Say the relevant facts, whether the task is complete, and what comes next — for work you handed over, who has it and whether it carries an earlier thread on or starts a new one — or the one question they have to answer first. Use confirmed values from tool results and the notes above, and never invent a successful action. Keep it short and plain.`:`## Return the result
48
48
 
49
- Return the relevant facts, whether the task is complete, and what comes next — for work you handed over, who has it and whether it carries an earlier thread on or starts a new one — or the one question the user has to answer first. Use confirmed values from tool results and the notes above, and never invent a successful action. What you return is said aloud: keep it short and plain.`,(v=N,O=x,v.some(e=>e.turns.length>0)?`## Earlier calls
49
+ Return the relevant facts, whether the task is complete, and what comes next — for work you handed over, who has it and whether it carries an earlier thread on or starts a new one — or the one question the user has to answer first. Use confirmed values from tool results and the notes above, and never invent a successful action. What you return is said aloud: keep it short and plain.`,(O=C,T=j,O.some(e=>e.turns.length>0)?`## Earlier calls
50
50
 
51
51
  What was said on the last calls, verbatim, newest last. It is the past: pick it up when the user does, and never answer it as a new request.
52
52
 
53
53
  A \`${s.TOOL_NAMES.thread_start}\` line carries the thread's handle and how it ended; the handle is for the thread tools, never said aloud. What they ask for now is often one of these carried further.
54
54
 
55
- ${(0,w.recentCallLines)(v.map(e=>({...e,jobs:O.filter(t=>t.callId===e.callId)})),o.RECENT_CALL.tokens)}`:""),g(e)].filter(Boolean).join("\n\n");return(0,w.logPromptSize)("thursday",j),j}[r,i,h,u,m]=y.then?(await y)():y;let g=e=>e?.trim()?`## Additional instructions
55
+ ${(0,w.recentCallLines)(O.map(e=>({...e,jobs:T.filter(t=>t.callId===e.callId)})),o.RECENT_CALL.tokens)}`:""),f(e)].filter(Boolean).join("\n\n");return(0,w.logPromptSize)("thursday",q),q}[r,i,h,u,m]=y.then?(await y)():y;let p=()=>`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 ${s.TOOL_NAMES.end_call} tool.`,f=e=>e?.trim()?`## Additional instructions
56
56
 
57
57
  Written by the user. Follow them together with everything above.
58
58
 
59
- ${e.trim()}`:"";e.s(["loadThursdayPrompt",0,p]),a()}catch(e){a(e)}},!1),97334,e=>e.a(async(t,a)=>{try{var o=e.i(68356),n=e.i(915874),s=e.i(469719),r=e.i(687388),i=e.i(911757),h=e.i(159479),l=e.i(386075),d=e.i(264079),u=e.i(56802),c=e.i(962072),m=e.i(353885),w=e.i(279041),y=e.i(340698),p=e.i(878498),g=e.i(640911),f=e.i(53748),b=e.i(22676),k=e.i(134344),v=t([h,l,u,c,y,b]);async function O(){let e=await Promise.all(k.TEXT_CALL_PROVIDERS.map(async e=>await (0,y.readConfig)(e.apiKeyName)?e.apiKeyName:null));return(0,k.textCallRunsOn)(t=>e.includes(t))}async function T(e,t){if(t)return t;let a=await O();return a||(0,f.publicError)(_),{provider:a,model:e.backendModel}}[h,l,u,c,y,b]=v.then?(await v)():v;let A=s.z.object({callId:s.z.string().min(1),settings:k.ThursdaySettingsSchema,standing:s.z.string().nullish(),runsOn:d.textModelRefSchema.nullish(),messages:s.z.array(s.z.unknown()).min(1)});async function E(e,t){var a,s;let i,h;try{i=await $(e)}catch(o){let{status:e,message:t}=(a=o,(0,f.isPublicError)(a)?{status:400,message:a.message}:a instanceof n.ZodError?{status:400,message:a.issues[0]?.message??"That request does not fit"}:(g.logger.error(a),{status:500,message:"Could not reach her"}));return new Response(t,{status:e})}let d=(0,o.streamText)({model:i.model,instructions:i.system,messages:i.messages,allowSystemInMessages:!0,tools:i.tools,providerOptions:i.providerOptions,stopWhen:(0,o.stepCountIs)(r.TEXT_CALL.maxSteps),abortSignal:t,onStepEnd:(s=i.callId,h=i.seq,async e=>{for(let t of e.content)if("tool-call"===t.type){let a=e.content.find(e=>"tool-result"===e.type&&e.toolCallId===t.toolCallId);await (0,b.saveTurns)(s,[{id:t.toolCallId,role:"tool",tool:t.toolName,text:t.toolName===m.TOOL_NAMES.web_search?function(e,t){let a=t??{},o=[(e??{}).query,a.action?.query].find(e=>"string"==typeof e&&!!e.trim()),n=Array.isArray(a.sources)?a.sources.flatMap(e=>e&&"object"==typeof e&&"url"in e&&"string"==typeof e.url?[{url:e.url,..."title"in e&&"string"==typeof e.title?{title:e.title}:{}}]:[]):[];return JSON.stringify({query:o??null,sources:n})}(t.input,a?.type==="tool-result"?a.output:null):JSON.stringify(t.input??{}),seq:h++}])}else"text"===t.type&&t.text.trim()?await (0,b.saveTurns)(s,[{id:crypto.randomUUID(),role:"assistant",text:t.text.trim(),seq:h++}]):"reasoning"===t.type&&t.text.trim()&&await (0,b.saveThought)(s,{id:crypto.randomUUID(),text:t.text.trim(),seq:h})})});return(0,o.createUIMessageStreamResponse)({stream:(0,o.toUIMessageStream)({stream:d.stream,tools:i.tools,onError:l.modelErrorToString})})}async function S(e,t,a){let o=await T(t,a),n="openai"===o.provider||"chatgpt"===o.provider,[s,r,d,u,g]=await Promise.all([(0,l.getTextModel)(o),(0,c.loadThursdayPrompt)(t.backendPrompt,!0),(0,h.loadTools)({target:"thursday",callId:e,webSearch:t.webSearch,written:!0}),(0,y.readConfig)(w.EXA_API_KEY),(0,y.readConfig)(i.LIVE_PROVIDER.apiKeyName)]),f=s.searchTools&&Object.values(s.searchTools)[0],b={...d,...t.webSearch&&!u&&f?{[m.TOOL_NAMES.web_search]:f}:{}},k=n?g?await (0,p.acceptedReasoning)({apiKey:g,model:o.model,effort:t.reasoningEffort}):"none"===t.reasoningEffort?{effort:"none"}:{effort:t.reasoningEffort??void 0,summary:"auto"}:null;return{model:s.model,system:r,tools:b,providerOptions:{openai:{...k?.effort?{reasoningEffort:k.effort}:{},...k&&"summary"in k&&k.summary?{reasoningSummary:k.summary}:{}}}}}async function $(e){let{callId:t,settings:a,standing:n,runsOn:s,messages:r}=A.parse(e),[i,h,l]=await Promise.all([S(t,a,s),(0,o.validateUIMessages)({messages:r}),(0,b.nextTurnSeq)(t)]),d=h.at(-1);d?.role!=="user"&&(0,f.publicError)("The last message is not yours.");let u=d.metadata?.relay===!0;return u||await (0,b.saveTurns)(t,[{id:d.id,role:"user",text:M(d),seq:l}]),{...i,callId:t,seq:u?l:l+1,messages:[...n?[{role:"system",content:n}]:[],...await (0,o.convertToModelMessages)(h,{ignoreIncompleteToolCalls:!0})]}}let _="Writing to Thursday needs a GPT subscription sign-in or an OpenAI key — Settings › API keys.",M=e=>e.parts.flatMap(e=>"text"===e.type?e.text:[]).join("\n").trim();e.s(["streamTextCall",0,E]),a()}catch(e){a(e)}},!1),878498,e=>{"use strict";var t=e.i(469719),a=e.i(687388),o=e.i(640911);e.i(904309),t.z.object({session:t.z.object({id:t.z.string().min(1)}),transport:t.z.object({type:t.z.literal("webrtc"),sdp:t.z.string().min(1)})});let n=new Map;async function s(e){let{apiKey:t,model:s,effort:r}=e,i=`${s} ${r??"auto"}`,h=n.get(i);if(void 0!==h)return h;let l="none"===r?{effort:r}:{...r?{effort:r}:{},summary:"auto"};for(;;){let e=await fetch("https://api.openai.com/v1/responses/input_tokens",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(a.LIVE_CALL.reasoningCheckMs),body:JSON.stringify({model:s,input:".",reasoning:l})}).catch(()=>null);if(!e)return l;let r=Object.keys(l).length?l:null;if(e.ok)return n.set(i,r),r;let h=await e.json().catch(()=>null),d=h?.error?.param?.replace(/^reasoning\./,"");if("effort"!==d&&"summary"!==d||!(d in l))return l;if(o.logger.warn(`${s} takes no reasoning ${d}; calls omit it`),delete l[d],!Object.keys(l).length)return n.set(i,null),null}}e.s(["acceptedReasoning",0,s])}];
59
+ ${e.trim()}`:"";e.s(["loadThursdayPrompt",0,g]),a()}catch(e){a(e)}},!1),97334,e=>e.a(async(t,a)=>{try{var o=e.i(68356),n=e.i(915874),s=e.i(469719),r=e.i(687388),i=e.i(911757),h=e.i(159479),l=e.i(386075),d=e.i(264079),u=e.i(56802),c=e.i(962072),m=e.i(353885),w=e.i(279041),y=e.i(340698),g=e.i(878498),p=e.i(640911),f=e.i(53748),b=e.i(22676),k=e.i(134344),v=t([h,l,u,c,y,b]);async function O(){let e=await Promise.all(k.TEXT_CALL_PROVIDERS.map(async e=>await (0,y.readConfig)(e.apiKeyName)?e.apiKeyName:null));return(0,k.textCallRunsOn)(t=>e.includes(t))}async function T(e,t){if(t)return t;let a=await O();return a||(0,f.publicError)(_),{provider:a,model:e.backendModel}}[h,l,u,c,y,b]=v.then?(await v)():v;let A=s.z.object({callId:s.z.string().min(1),settings:i.LiveSettingsSchema,standing:s.z.string().nullish(),runsOn:d.textModelRefSchema.nullish(),messages:s.z.array(s.z.unknown()).min(1)});async function S(e,t){var a,s;let i,h;try{i=await $(e)}catch(o){let{status:e,message:t}=(a=o,(0,f.isPublicError)(a)?{status:400,message:a.message}:a instanceof n.ZodError?{status:400,message:a.issues[0]?.message??"That request does not fit"}:(p.logger.error(a),{status:500,message:"Could not reach her"}));return new Response(t,{status:e})}let d=(0,o.streamText)({model:i.model,instructions:i.system,messages:i.messages,allowSystemInMessages:!0,tools:i.tools,providerOptions:i.providerOptions,stopWhen:(0,o.stepCountIs)(r.TEXT_CALL.maxSteps),abortSignal:t,onStepEnd:(s=i.callId,h=i.seq,async e=>{for(let t of e.content)if("tool-call"===t.type){let a=e.content.find(e=>"tool-result"===e.type&&e.toolCallId===t.toolCallId);await (0,b.saveTurns)(s,[{id:t.toolCallId,role:"tool",tool:t.toolName,text:t.toolName===m.TOOL_NAMES.web_search?function(e,t){let a=t??{},o=[(e??{}).query,a.action?.query].find(e=>"string"==typeof e&&!!e.trim()),n=Array.isArray(a.sources)?a.sources.flatMap(e=>e&&"object"==typeof e&&"url"in e&&"string"==typeof e.url?[{url:e.url,..."title"in e&&"string"==typeof e.title?{title:e.title}:{}}]:[]):[];return JSON.stringify({query:o??null,sources:n})}(t.input,a?.type==="tool-result"?a.output:null):JSON.stringify(t.input??{}),seq:h++}])}else"text"===t.type&&t.text.trim()?await (0,b.saveTurns)(s,[{id:crypto.randomUUID(),role:"assistant",text:t.text.trim(),seq:h++}]):"reasoning"===t.type&&t.text.trim()&&await (0,b.saveThought)(s,{id:crypto.randomUUID(),text:t.text.trim(),seq:h})})});return(0,o.createUIMessageStreamResponse)({stream:(0,o.toUIMessageStream)({stream:d.stream,tools:i.tools,onError:l.modelErrorToString})})}async function E(e,t,a){let o=await T(t,a),n="openai"===o.provider||"chatgpt"===o.provider,[s,r,d,u,p]=await Promise.all([(0,l.getTextModel)(o),(0,c.loadThursdayPrompt)(t.backendPrompt,!0),(0,h.loadTools)({target:"thursday",callId:e,webSearch:t.webSearch,written:!0}),(0,y.readConfig)(w.EXA_API_KEY),(0,y.readConfig)(i.LIVE_PROVIDER.apiKeyName)]),f=s.searchTools&&Object.values(s.searchTools)[0],b={...d,...t.webSearch&&!u&&f?{[m.TOOL_NAMES.web_search]:f}:{}},k=n?p?await (0,g.acceptedReasoning)({apiKey:p,model:o.model,effort:t.reasoningEffort}):"none"===t.reasoningEffort?{effort:"none"}:{effort:t.reasoningEffort??void 0,summary:"auto"}:null;return{model:s.model,system:r,tools:b,providerOptions:{openai:{...k?.effort?{reasoningEffort:k.effort}:{},...k&&"summary"in k&&k.summary?{reasoningSummary:k.summary}:{}}}}}async function $(e){let{callId:t,settings:a,standing:n,runsOn:s,messages:r}=A.parse(e),[i,h,l]=await Promise.all([E(t,a,s),(0,o.validateUIMessages)({messages:r}),(0,b.nextTurnSeq)(t)]),d=h.at(-1);d?.role!=="user"&&(0,f.publicError)("The last message is not yours.");let u=d.metadata?.relay===!0;return u||await (0,b.saveTurns)(t,[{id:d.id,role:"user",text:M(d),seq:l}]),{...i,callId:t,seq:u?l:l+1,messages:[...n?[{role:"system",content:n}]:[],...await (0,o.convertToModelMessages)(h,{ignoreIncompleteToolCalls:!0})]}}let _="Writing to Thursday needs a GPT subscription sign-in or an OpenAI key — Settings › API keys.",M=e=>e.parts.flatMap(e=>"text"===e.type?e.text:[]).join("\n").trim();e.s(["streamTextCall",0,S]),a()}catch(e){a(e)}},!1),878498,e=>{"use strict";var t=e.i(469719),a=e.i(687388),o=e.i(640911);e.i(904309),t.z.object({session:t.z.object({id:t.z.string().min(1)}),transport:t.z.object({type:t.z.literal("webrtc"),sdp:t.z.string().min(1)})});let n=new Map;async function s(e){let{apiKey:t,model:s,effort:r}=e,i=`${s} ${r??"auto"}`,h=n.get(i);if(void 0!==h)return h;let l="none"===r?{effort:r}:{...r?{effort:r}:{},summary:"auto"};for(;;){let e=await fetch("https://api.openai.com/v1/responses/input_tokens",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(a.LIVE_CALL.reasoningCheckMs),body:JSON.stringify({model:s,input:".",reasoning:l})}).catch(()=>null);if(!e)return l;let r=Object.keys(l).length?l:null;if(e.ok)return n.set(i,r),r;let h=await e.json().catch(()=>null),d=h?.error?.param?.replace(/^reasoning\./,"");if("effort"!==d&&"summary"!==d||!(d in l))return l;if(o.logger.warn(`${s} takes no reasoning ${d}; calls omit it`),delete l[d],!Object.keys(l).length)return n.set(i,null),null}}e.s(["acceptedReasoning",0,s])}];
60
60
 
61
61
  //# sourceMappingURL=_1m88lkh._.js.map