@rpcbase/agents-sdk 0.10.0 → 0.12.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 (226) hide show
  1. package/dist/agents-sdk.css +1 -1
  2. package/dist/api/apiErrors.d.ts.map +1 -1
  3. package/dist/api/chat/handler.d.ts +1 -1
  4. package/dist/api/chat/handler.d.ts.map +1 -1
  5. package/dist/api/chat/historyCompaction.d.ts.map +1 -1
  6. package/dist/api/chat/messages/handler.d.ts +1 -1
  7. package/dist/api/chat/messages/handler.d.ts.map +1 -1
  8. package/dist/api/chat/messages/trailing/handler.d.ts +1 -1
  9. package/dist/api/chat/messages/trailing/handler.d.ts.map +1 -1
  10. package/dist/api/chat/models.d.ts.map +1 -1
  11. package/dist/api/chat/prompts.d.ts.map +1 -1
  12. package/dist/api/chat/resumableSse.d.ts.map +1 -1
  13. package/dist/api/chat/runtimeConfig.d.ts +8 -0
  14. package/dist/api/chat/runtimeConfig.d.ts.map +1 -1
  15. package/dist/api/chat/stream/handler.d.ts +1 -1
  16. package/dist/api/chat/stream/handler.d.ts.map +1 -1
  17. package/dist/api/chat/titles.d.ts.map +1 -1
  18. package/dist/api/chat/toolRouting.d.ts +7 -0
  19. package/dist/api/chat/toolRouting.d.ts.map +1 -0
  20. package/dist/api/chat/tools.d.ts +134 -134
  21. package/dist/api/chat/tools.d.ts.map +1 -1
  22. package/dist/api/chatCtx.d.ts.map +1 -1
  23. package/dist/api/chatDb.d.ts +2 -0
  24. package/dist/api/chatDb.d.ts.map +1 -1
  25. package/dist/api/chatStore.d.ts +1 -0
  26. package/dist/api/chatStore.d.ts.map +1 -1
  27. package/dist/api/document/handler.d.ts +1 -1
  28. package/dist/api/document/handler.d.ts.map +1 -1
  29. package/dist/api/history/handler.d.ts +1 -1
  30. package/dist/api/history/handler.d.ts.map +1 -1
  31. package/dist/api/ping/handler.d.ts +1 -1
  32. package/dist/api/ping/handler.d.ts.map +1 -1
  33. package/dist/api/session/current/handler.d.ts +1 -1
  34. package/dist/api/session/current/handler.d.ts.map +1 -1
  35. package/dist/api/session/tenant/handler.d.ts +1 -1
  36. package/dist/api/session/tenant/handler.d.ts.map +1 -1
  37. package/dist/api/stream-test/handler.d.ts +1 -1
  38. package/dist/api/stream-test/handler.d.ts.map +1 -1
  39. package/dist/api/suggestions/handler.d.ts +1 -1
  40. package/dist/api/suggestions/handler.d.ts.map +1 -1
  41. package/dist/api/test/reset/handler.d.ts +1 -1
  42. package/dist/api/test/reset/handler.d.ts.map +1 -1
  43. package/dist/api/upload/handler.d.ts +1 -1
  44. package/dist/api/upload/handler.d.ts.map +1 -1
  45. package/dist/api/vote/handler.d.ts +1 -1
  46. package/dist/api/vote/handler.d.ts.map +1 -1
  47. package/dist/{apiErrors-CFUx-UrE.js → apiErrors-Ck5tynNE.js} +1 -0
  48. package/dist/{apiErrors-FdS4Eh1H.js → apiErrors-DKcH9vz9.js} +1 -0
  49. package/dist/chat-models.browser.js +1 -1
  50. package/dist/chat-models.js +1 -1
  51. package/dist/chatDb-CJCdqpjR.js +280 -0
  52. package/dist/chatDb-DLQOzat8.js +280 -0
  53. package/dist/{chunk-BO2N2NFS-DRhdPgDj.js → chunk-BO2N2NFS-BXeXbvYU.js} +2 -2
  54. package/dist/{chunk-BO2N2NFS-BDR8fnNb.js → chunk-BO2N2NFS-C0c-iJhV.js} +2 -2
  55. package/dist/client-routes.browser.js +4 -2
  56. package/dist/client-routes.d.ts.map +1 -1
  57. package/dist/client-routes.js +4 -2
  58. package/dist/components/AppErrorExtra.d.ts.map +1 -1
  59. package/dist/components/ai-elements/artifact.d.ts.map +1 -1
  60. package/dist/components/ai-elements/canvas.d.ts.map +1 -1
  61. package/dist/components/ai-elements/checkpoint.d.ts +1 -1
  62. package/dist/components/ai-elements/checkpoint.d.ts.map +1 -1
  63. package/dist/components/ai-elements/code-block.d.ts.map +1 -1
  64. package/dist/components/ai-elements/confirmation.d.ts.map +1 -1
  65. package/dist/components/ai-elements/controls.d.ts.map +1 -1
  66. package/dist/components/ai-elements/conversation.d.ts.map +1 -1
  67. package/dist/components/ai-elements/edge.d.ts +5 -2
  68. package/dist/components/ai-elements/edge.d.ts.map +1 -1
  69. package/dist/components/ai-elements/image.d.ts.map +1 -1
  70. package/dist/components/ai-elements/inline-citation.d.ts.map +1 -1
  71. package/dist/components/ai-elements/loader.d.ts.map +1 -1
  72. package/dist/components/ai-elements/message.d.ts.map +1 -1
  73. package/dist/components/ai-elements/model-selector.d.ts +3 -2
  74. package/dist/components/ai-elements/model-selector.d.ts.map +1 -1
  75. package/dist/components/ai-elements/node.d.ts.map +1 -1
  76. package/dist/components/ai-elements/open-in-chat.d.ts.map +1 -1
  77. package/dist/components/ai-elements/panel.d.ts.map +1 -1
  78. package/dist/components/ai-elements/plan.d.ts.map +1 -1
  79. package/dist/components/ai-elements/prompt-input.d.ts.map +1 -1
  80. package/dist/components/ai-elements/queue.d.ts.map +1 -1
  81. package/dist/components/ai-elements/shimmer.d.ts +3 -1
  82. package/dist/components/ai-elements/shimmer.d.ts.map +1 -1
  83. package/dist/components/ai-elements/sources.d.ts.map +1 -1
  84. package/dist/components/ai-elements/suggestion.d.ts.map +1 -1
  85. package/dist/components/ai-elements/task.d.ts.map +1 -1
  86. package/dist/components/ai-elements/tool.d.ts.map +1 -1
  87. package/dist/components/ai-elements/toolbar.d.ts.map +1 -1
  88. package/dist/components/ai-elements/web-preview.d.ts.map +1 -1
  89. package/dist/components/artifact.d.ts +4 -4
  90. package/dist/components/artifact.d.ts.map +1 -1
  91. package/dist/components/chat.d.ts +2 -1
  92. package/dist/components/chat.d.ts.map +1 -1
  93. package/dist/components/create-artifact.d.ts.map +1 -1
  94. package/dist/components/data-stream-provider.d.ts +3 -1
  95. package/dist/components/data-stream-provider.d.ts.map +1 -1
  96. package/dist/components/diffview.d.ts.map +1 -1
  97. package/dist/components/document-skeleton.d.ts.map +1 -1
  98. package/dist/components/elements/actions.d.ts.map +1 -1
  99. package/dist/components/elements/branch.d.ts.map +1 -1
  100. package/dist/components/elements/code-block.d.ts.map +1 -1
  101. package/dist/components/elements/conversation.d.ts.map +1 -1
  102. package/dist/components/elements/image.d.ts.map +1 -1
  103. package/dist/components/elements/inline-citation.d.ts.map +1 -1
  104. package/dist/components/elements/loader.d.ts.map +1 -1
  105. package/dist/components/elements/message.d.ts.map +1 -1
  106. package/dist/components/elements/prompt-input.d.ts.map +1 -1
  107. package/dist/components/elements/response.d.ts +4 -4
  108. package/dist/components/elements/response.d.ts.map +1 -1
  109. package/dist/components/elements/source.d.ts.map +1 -1
  110. package/dist/components/elements/suggestion.d.ts.map +1 -1
  111. package/dist/components/elements/task.d.ts.map +1 -1
  112. package/dist/components/elements/tool.d.ts.map +1 -1
  113. package/dist/components/elements/web-preview.d.ts.map +1 -1
  114. package/dist/components/greeting.d.ts.map +1 -1
  115. package/dist/components/icons.d.ts.map +1 -1
  116. package/dist/components/message.d.ts +2 -3
  117. package/dist/components/message.d.ts.map +1 -1
  118. package/dist/components/messages.d.ts +6 -1
  119. package/dist/components/messages.d.ts.map +1 -1
  120. package/dist/components/multimodal-input.d.ts.map +1 -1
  121. package/dist/components/preview-attachment.d.ts.map +1 -1
  122. package/dist/components/sheet-editor.d.ts +2 -1
  123. package/dist/components/sheet-editor.d.ts.map +1 -1
  124. package/dist/components/sidebar-history-item.d.ts +4 -1
  125. package/dist/components/sidebar-history-item.d.ts.map +1 -1
  126. package/dist/components/sidebar-history.d.ts +2 -1
  127. package/dist/components/sidebar-history.d.ts.map +1 -1
  128. package/dist/components/suggestion.d.ts.map +1 -1
  129. package/dist/components/toolbar.d.ts +4 -2
  130. package/dist/components/toolbar.d.ts.map +1 -1
  131. package/dist/components/ui/alert-dialog.d.ts +13 -13
  132. package/dist/components/ui/alert-dialog.d.ts.map +1 -1
  133. package/dist/components/ui/button.d.ts +2 -2
  134. package/dist/components/ui/command.d.ts +6 -5
  135. package/dist/components/ui/command.d.ts.map +1 -1
  136. package/dist/components/ui/dialog.d.ts +13 -13
  137. package/dist/components/ui/dialog.d.ts.map +1 -1
  138. package/dist/components/ui/dropdown-menu.d.ts +10 -10
  139. package/dist/components/ui/dropdown-menu.d.ts.map +1 -1
  140. package/dist/components/ui/hover-card.d.ts.map +1 -1
  141. package/dist/components/ui/input-group.d.ts +2 -2
  142. package/dist/components/ui/sheet.d.ts +13 -13
  143. package/dist/components/ui/sheet.d.ts.map +1 -1
  144. package/dist/components/ui/sidebar.d.ts +1 -1
  145. package/dist/components/ui/tooltip.d.ts.map +1 -1
  146. package/dist/components/version-footer.d.ts.map +1 -1
  147. package/dist/{data-stream-handler-DXAHFC5k.js → data-stream-handler-83PApswO.js} +12585 -12313
  148. package/dist/{data-stream-handler-lr4wJ3vt.js → data-stream-handler-Cm6JVGl8.js} +12585 -12313
  149. package/dist/{handler-BdCGoVUM.js → handler-8zojwqU7.js} +1 -1
  150. package/dist/{handler-Dy536I3-.js → handler-BMF6eWg5.js} +3 -3
  151. package/dist/{handler-DdKB5P3H.js → handler-BTWWHJUs.js} +2 -2
  152. package/dist/{handler-5n-YwiF3.js → handler-C-CFaSnD.js} +2 -2
  153. package/dist/{handler-hah8tVEE.js → handler-C34eWXJg.js} +2 -2
  154. package/dist/{handler-DMwBT4bK.js → handler-CG2GBD33.js} +1 -1
  155. package/dist/handler-CVs03Ys2.js +1568 -0
  156. package/dist/{handler-Jua6SU39.js → handler-Cl7-HRxy.js} +2 -2
  157. package/dist/{handler-D752oOcY.js → handler-CvmHrkz9.js} +2 -2
  158. package/dist/{handler-C8gaYgmy.js → handler-CwoR5Bdv.js} +2 -2
  159. package/dist/{handler-svaSKC2q.js → handler-D003Oipd.js} +1 -1
  160. package/dist/{handler-C0MO52d9.js → handler-D88wEmsv.js} +2 -2
  161. package/dist/{handler-B8Twsrmo.js → handler-DAXyqx4y.js} +1 -1
  162. package/dist/{handler-BgYHL3BZ.js → handler-DBuF7L41.js} +2 -2
  163. package/dist/{handler-B3uUDuTR.js → handler-DOtL2C2i.js} +3 -3
  164. package/dist/{handler-6yb49c5-.js → handler-DS1_E7Zc.js} +2 -2
  165. package/dist/{handler-By86dyTJ.js → handler-DilZY3o3.js} +2 -2
  166. package/dist/{handler-YmuAR8ei.js → handler-DiyNUz4m.js} +2 -2
  167. package/dist/{handler-BMeUL2iE.js → handler-DnkxwQzf.js} +2 -2
  168. package/dist/{handler-uF8GJoVX.js → handler-Du7LuJB1.js} +1 -1
  169. package/dist/{handler-lUriE7jY.js → handler-YvSCKKjM.js} +2 -2
  170. package/dist/{handler-DSncMeo4.js → handler-Z-tCrlQ_.js} +752 -500
  171. package/dist/{highlighted-body-OFNGDK62-255wLBzG.js → highlighted-body-OFNGDK62-kzg9WvPK.js} +1 -1
  172. package/dist/{highlighted-body-OFNGDK62-ChEBPTZ3.js → highlighted-body-OFNGDK62-yqCKh6K1.js} +1 -1
  173. package/dist/hooks/use-chat-documents.d.ts +2 -2
  174. package/dist/hooks/use-chat-votes.d.ts +2 -2
  175. package/dist/index.browser.js +2 -2
  176. package/dist/index.js +2 -2
  177. package/dist/lib/ai/openai-reasoning.d.ts +2 -1
  178. package/dist/lib/ai/openai-reasoning.d.ts.map +1 -1
  179. package/dist/lib/chat-streaming.d.ts +14 -0
  180. package/dist/lib/chat-streaming.d.ts.map +1 -0
  181. package/dist/lib/db/schema.d.ts +1 -0
  182. package/dist/lib/db/schema.d.ts.map +1 -1
  183. package/dist/lib/editor/config.d.ts.map +1 -1
  184. package/dist/lib/editor/functions.d.ts.map +1 -1
  185. package/dist/lib/editor/react-renderer.d.ts.map +1 -1
  186. package/dist/lib/errors.d.ts +1 -1
  187. package/dist/lib/errors.d.ts.map +1 -1
  188. package/dist/lib/message-visibility.d.ts +15 -0
  189. package/dist/lib/message-visibility.d.ts.map +1 -0
  190. package/dist/lib/tenant.d.ts.map +1 -1
  191. package/dist/lib/types.d.ts +9 -0
  192. package/dist/lib/types.d.ts.map +1 -1
  193. package/dist/lib/utils.d.ts.map +1 -1
  194. package/dist/loaders/rootLoader.d.ts +1 -0
  195. package/dist/loaders/rootLoader.d.ts.map +1 -1
  196. package/dist/mermaid-GHXKKRXX-BdyS-O1X.js +2 -0
  197. package/dist/mermaid-GHXKKRXX-g_KMuIEW.js +2 -0
  198. package/dist/message-visibility-zTseZa3P.js +27 -0
  199. package/dist/models/RBAgentsChatThread.d.ts +1 -0
  200. package/dist/models/RBAgentsChatThread.d.ts.map +1 -1
  201. package/dist/models/RBAgentsUsageEvent.d.ts +2 -2
  202. package/dist/models/RBAgentsUsageEvent.d.ts.map +1 -1
  203. package/dist/models/index.d.ts +14 -14
  204. package/dist/models.browser.js +1 -0
  205. package/dist/models.js +6 -0
  206. package/dist/openai-reasoning-BCA05blq.js +19 -0
  207. package/dist/pages/ChatNewPage.d.ts.map +1 -1
  208. package/dist/pages/ChatPage.d.ts.map +1 -1
  209. package/dist/routes.browser.js +14 -14
  210. package/dist/routes.js +14 -14
  211. package/dist/runtime.js +2 -2
  212. package/dist/tailwind-source.js +1 -1
  213. package/package.json +19 -18
  214. package/dist/chatDb-BSiHIyn9.js +0 -265
  215. package/dist/chatDb-YfeABtn-.js +0 -265
  216. package/dist/handler-DE8agLBS.js +0 -1304
  217. package/dist/mermaid-GHXKKRXX-BqT9Nt_j.js +0 -2
  218. package/dist/mermaid-GHXKKRXX-fqlMH1Mi.js +0 -2
  219. package/dist/openai-reasoning-kFq60GX9.js +0 -19
  220. /package/dist/{chatCtx-DSgD1fix.js → chatCtx-C8Ba-LB7.js} +0 -0
  221. /package/dist/{chatCtx-BWOFI93u.js → chatCtx-CJF05uCy.js} +0 -0
  222. /package/dist/{handler-BdXUC9Rg.js → handler-CtJQ0h8J.js} +0 -0
  223. /package/dist/{handler-DF3WRSDj.js → handler-DdF_Xz9w.js} +0 -0
  224. /package/dist/{handler-D74Wi6e9.js → handler-eWXBUnfH.js} +0 -0
  225. /package/dist/{models-DphUIx22.js → models-BTzlEPg8.js} +0 -0
  226. /package/dist/{resumableSse-BprFOR5Q.js → resumableSse-CmmkOGyv.js} +0 -0
@@ -1,65 +1,65 @@
1
- import { c as e } from "./chunk-BO2N2NFS-BDR8fnNb.js";
2
- import { r as t } from "./openai-reasoning-kFq60GX9.js";
3
- import { a as n, i as r, t as i } from "./chatCtx-BWOFI93u.js";
4
- import { t as a } from "./apiErrors-FdS4Eh1H.js";
5
- import { _ as o, a as s, b as c, g as l, h as u, l as d, m as f, n as p, p as m, s as h, v as g, x as _, y as ee } from "./chatDb-BSiHIyn9.js";
6
- import { n as v, t as y } from "./resumableSse-BprFOR5Q.js";
7
- import { Output as b, convertToModelMessages as te, createUIMessageStream as ne, extractReasoningMiddleware as re, generateText as ie, smoothStream as ae, stepCountIs as oe, streamObject as x, streamText as S, tool as C, wrapLanguageModel as w } from "ai";
8
- import { getTenantFilesystemDb as T } from "@rpcbase/db";
9
- import { createHash as E, randomUUID as D } from "node:crypto";
10
- import { GridFSBucket as se, ObjectId as O } from "mongodb";
11
- import { createGoogleGenerativeAI as ce } from "@ai-sdk/google";
12
- import { openai as k } from "@ai-sdk/openai";
13
- import { createXai as le } from "@ai-sdk/xai";
14
- import { z as A } from "zod";
1
+ import { c as e, o as t } from "./message-visibility-zTseZa3P.js";
2
+ import { i as n } from "./openai-reasoning-BCA05blq.js";
3
+ import { t as r } from "./apiErrors-DKcH9vz9.js";
4
+ import { i, r as a, t as o } from "./chatCtx-C8Ba-LB7.js";
5
+ import { S as s, _ as c, a as l, b as u, f as d, g as f, h as p, l as m, m as h, n as g, s as _, v, x as y, y as b } from "./chatDb-DLQOzat8.js";
6
+ import { n as x, t as S } from "./resumableSse-CmmkOGyv.js";
7
+ import { Output as C, convertToModelMessages as ee, createUIMessageStream as te, extractReasoningMiddleware as w, generateText as ne, smoothStream as T, stepCountIs as re, streamObject as E, streamText as ie, tool as D, wrapLanguageModel as O } from "ai";
8
+ import { getTenantFilesystemDb as k } from "@rpcbase/db";
9
+ import { createHash as ae, randomUUID as A } from "node:crypto";
10
+ import { GridFSBucket as j, ObjectId as oe } from "mongodb";
11
+ import { createGoogleGenerativeAI as M } from "@ai-sdk/google";
12
+ import { openai as N } from "@ai-sdk/openai";
13
+ import { createXai as se } from "@ai-sdk/xai";
14
+ import { z as P } from "zod";
15
15
  //#region src/api/chat/models.ts
16
- var j = /-thinking$/, M = "openai/", N = "google/", P = "xai/", F = new Set([
16
+ var F = /-thinking$/, ce = "openai/", le = "google/", I = "xai/", L = new Set([
17
17
  "openai/gpt-5.4-mini",
18
18
  "openai/gpt-5.5",
19
19
  "google/gemini-3.5-flash",
20
20
  "xai/grok-4.3-thinking"
21
- ]), ue = (e) => e.startsWith(M), de = (e) => e.startsWith(N), fe = (e) => e.startsWith(P), pe = (e) => e.endsWith("-thinking"), me = (e) => e.includes("/") ? ue(e) || de(e) || fe(e) : !1, I = le({
21
+ ]), ue = (e) => e.startsWith(ce), de = (e) => e.startsWith(le), fe = (e) => e.startsWith(I), pe = (e) => e.endsWith("-thinking"), me = (e) => e.includes("/") ? ue(e) || de(e) || fe(e) : !1, R = se({
22
22
  baseURL: process.env.XAI_BASE_URL ?? "https://api.x.ai/v1",
23
23
  apiKey: process.env.XAI_API_KEY
24
- }), L = ce({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY }), he = (e) => {
25
- if (ue(e)) return k.responses(e.slice(M.length));
24
+ }), z = M({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY }), he = (e) => {
25
+ if (ue(e)) return N.responses(e.slice(ce.length));
26
26
  if (de(e)) {
27
- let t = e.slice(N.length).replace(j, ""), n = L.chat(t);
28
- return pe(e) ? w({
27
+ let t = e.slice(le.length).replace(F, ""), n = z.chat(t);
28
+ return pe(e) ? O({
29
29
  model: n,
30
- middleware: re({ tagName: "thinking" })
30
+ middleware: w({ tagName: "thinking" })
31
31
  }) : n;
32
32
  }
33
33
  if (fe(e)) {
34
- let t = e.slice(P.length).replace(j, "");
35
- return pe(e) ? I.responses(t) : I.chat(t);
34
+ let t = e.slice(I.length).replace(F, "");
35
+ return pe(e) ? R.responses(t) : R.chat(t);
36
36
  }
37
37
  throw Error(`Unsupported modelId: ${e}`);
38
- }, ge = () => k.chat("gpt-5.4-mini"), R = () => k.chat(process.env.AGENT_SDK_ARTIFACT_MODEL ?? "gpt-5.4-mini"), z = "\nArtifacts is a special user interface mode that helps users with writing, editing, and other content creation tasks. When artifact is open, it is on the right side of the screen, while the conversation is on the left side. When creating, editing, or updating documents, changes are reflected in real-time on the artifacts and visible to the user.\n\nWhen asked to write code, always use artifacts. When writing code, specify the language in the backticks, e.g. ```python`code here```. The default language is Python. Other languages are not yet supported, so let the user know if they request a different language.\n\nCritical rules:\n- Only call one artifact tool per response.\n- Do not update or edit a document immediately after creating it. Wait for user feedback or an explicit request to modify it.\n- After creating, editing, or updating an artifact, do not repeat the full artifact content in chat. The user can already see it.\n\nThis is a guide for using artifacts tools: `createDocument`, `editDocument`, `updateDocument`, and `requestSuggestions`, which render content on artifacts beside the conversation.\n\n**When to use `createDocument`:**\n- For substantial content (>10 lines) or code\n- For content users will likely save/reuse (emails, code, essays, etc.)\n- When explicitly requested to create a document\n- For when content contains a single code snippet\n- Use kind \"code\" for programming, \"text\" for writing, and \"sheet\" for tabular/CSV data\n\n**When NOT to use `createDocument`:**\n- For informational/explanatory content\n- For conversational responses\n- When asked to keep it in chat\n\n**Using `editDocument`:**\n- Prefer this for targeted edits to an existing artifact\n- For scripts: fixing bugs, adding/removing lines, renaming variables, adding logs\n- For documents: fixing typos, rewording paragraphs, inserting or replacing sections\n- Provide an exact `old_string` and `new_string`\n- Include enough surrounding context in `old_string` to make the match unique\n- Use `replace_all: true` only for deliberate repeated replacements, like renaming a variable everywhere\n\n**Using `updateDocument`:**\n- Default to full document rewrites for major changes\n- Use `editDocument` instead for specific, isolated changes\n- Follow user instructions for which parts to modify\n\n**When NOT to use `editDocument` or `updateDocument`:**\n- Immediately after creating a document\n- Without an explicit user request to modify the artifact\n\n**Using `requestSuggestions`:**\n- ONLY use when the user explicitly asks for suggestions on an existing document\n- Requires a valid document ID from a previously created document\n- Never use for general questions or information requests\n", B = "You are a friendly assistant! Keep your responses concise and helpful.\n\nWhen asked to write, create, or help with something, just do it directly. Don't ask clarifying questions unless absolutely necessary - make reasonable assumptions and proceed with the task.", V = (e) => `\
38
+ }, ge = () => N.chat("gpt-5.4-mini"), B = () => N.chat(process.env.AGENT_SDK_ARTIFACT_MODEL ?? "gpt-5.4-mini"), V = "\nArtifacts is a special user interface mode that helps users with writing, editing, and other content creation tasks. When artifact is open, it is on the right side of the screen, while the conversation is on the left side. When creating, editing, or updating documents, changes are reflected in real-time on the artifacts and visible to the user.\n\nWhen asked to write code, always use artifacts. When writing code, specify the language in the backticks, e.g. ```python`code here```. The default language is Python. Other languages are not yet supported, so let the user know if they request a different language.\n\nCritical rules:\n- Only call one artifact tool per response.\n- Do not update or edit a document immediately after creating it. Wait for user feedback or an explicit request to modify it.\n- After creating, editing, or updating an artifact, do not repeat the full artifact content in chat. The user can already see it.\n\nThis is a guide for using artifacts tools: `createDocument`, `editDocument`, `updateDocument`, and `requestSuggestions`, which render content on artifacts beside the conversation.\n\n**When to use `createDocument`:**\n- For substantial content (>10 lines) or code\n- For content users will likely save/reuse (emails, code, essays, etc.)\n- When explicitly requested to create a document\n- For when content contains a single code snippet\n- Use kind \"code\" for programming, \"text\" for writing, and \"sheet\" for tabular/CSV data\n\n**When NOT to use `createDocument`:**\n- For informational/explanatory content\n- For conversational responses\n- When asked to keep it in chat\n\n**Using `editDocument`:**\n- Prefer this for targeted edits to an existing artifact\n- For scripts: fixing bugs, adding/removing lines, renaming variables, adding logs\n- For documents: fixing typos, rewording paragraphs, inserting or replacing sections\n- Provide an exact `old_string` and `new_string`\n- Include enough surrounding context in `old_string` to make the match unique\n- Use `replace_all: true` only for deliberate repeated replacements, like renaming a variable everywhere\n\n**Using `updateDocument`:**\n- Default to full document rewrites for major changes\n- Use `editDocument` instead for specific, isolated changes\n- Follow user instructions for which parts to modify\n\n**When NOT to use `editDocument` or `updateDocument`:**\n- Immediately after creating a document\n- Without an explicit user request to modify the artifact\n\n**Using `requestSuggestions`:**\n- ONLY use when the user explicitly asks for suggestions on an existing document\n- Requires a valid document ID from a previously created document\n- Never use for general questions or information requests\n", H = "You are a friendly assistant! Keep your responses concise and helpful.\n\nWhen asked to write, create, or help with something, just do it directly. Don't ask clarifying questions unless absolutely necessary - make reasonable assumptions and proceed with the task.", U = (e) => `\
39
39
  About the origin of user's request:
40
40
  - lat: ${e.latitude ?? "unknown"}
41
41
  - lon: ${e.longitude ?? "unknown"}
42
42
  - city: ${e.city ?? "unknown"}
43
43
  - country: ${e.country ?? "unknown"}
44
44
  `, _e = ({ selectedChatModel: e, requestHints: t, agentInstructions: n, knowledge: r }) => {
45
- let i = V(t), a = [n?.trim() ? `Agent instructions:\n${n.trim()}` : "", r?.trim() ? `Knowledge context:\n${r.trim()}` : ""].filter(Boolean).join("\n\n");
45
+ let i = U(t), a = [n?.trim() ? `Agent instructions:\n${n.trim()}` : "", r?.trim() ? `Knowledge context:\n${r.trim()}` : ""].filter(Boolean).join("\n\n");
46
46
  if (e.includes("reasoning") || e.includes("thinking")) {
47
- let t = e.startsWith("google/") && e.includes("thinking") ? `${B}\n\nWhen you reason, put your reasoning inside <thinking>...</thinking> tags. Then provide your final answer outside of those tags.\n\n${i}` : `${B}\n\n${i}`;
47
+ let t = e.startsWith("google/") && e.includes("thinking") ? `${H}\n\nWhen you reason, put your reasoning inside <thinking>...</thinking> tags. Then provide your final answer outside of those tags.\n\n${i}` : `${H}\n\n${i}`;
48
48
  return a ? `${t}\n\n${a}` : t;
49
49
  }
50
- let o = `${B}\n\n${i}\n\n${z}`;
50
+ let o = `${H}\n\n${i}\n\n${V}`;
51
51
  return a ? `${o}\n\n${a}` : o;
52
52
  }, ve = "\nYou are a Python code generator that creates self-contained, executable code snippets. When writing code:\n\n1. Each snippet should be complete and runnable on its own\n2. Prefer using print() statements to display outputs\n3. Include helpful comments explaining the code\n4. Keep snippets concise (generally under 15 lines)\n5. Avoid external dependencies - use Python standard library\n6. Handle potential errors gracefully\n7. Return meaningful output that demonstrates the code's functionality\n8. Don't use input() or other interactive functions\n9. Don't access files or network resources\n10. Don't use infinite loops\n\nExamples of good snippets:\n\n# Calculate factorial iteratively\ndef factorial(n):\n result = 1\n for i in range(1, n + 1):\n result *= i\n return result\n\nprint(f\"Factorial of 5 is: {factorial(5)}\")\n", ye = "\nYou are a spreadsheet creation assistant. Create a spreadsheet in csv format based on the given prompt. The spreadsheet should contain meaningful column headers and data.\n", be = (e, t) => {
53
53
  let n = "document";
54
54
  return t === "code" ? n = "script" : t === "sheet" && (n = "spreadsheet"), `Rewrite the following ${n} based on the given prompt.
55
55
 
56
56
  ${e}`;
57
- }, xe = "Generate a short chat title (2-5 words) summarizing the user's message.\n\nOutput ONLY the title text. No prefixes, no formatting.\n\nExamples:\n- \"what's the weather in nyc\" → Weather in NYC\n- \"help me write an essay about space\" → Space Essay Help\n- \"hi\" → (empty string)\n- \"debug my python code\" → Python Debugging\n\nBad outputs (never do this):\n- \"# Space Essay\" (no hashtags)\n- \"Title: Weather\" (no prefixes)\n- \"\"NYC Weather\"\" (no quotes)\n\nRules:\n- Maximum 30 characters\n- No quotes, colons, hashtags, or markdown\n- Just the topic/intent, not a full sentence", Se = 24, Ce = 8e4, we = 16e3, Te = "agent-runtime-history-compaction-summary", H = (e) => !!e && typeof e == "object" && !Array.isArray(e), U = (e) => typeof e == "string" && e.trim() ? e.trim() : null, Ee = (e) => {
58
- let t = U((H(e.metadata) ? e.metadata : null)?.createdAt);
57
+ }, xe = "Generate a short chat title (2-5 words) summarizing the user's message.\n\nOutput ONLY the title text. No prefixes, no formatting.\n\nExamples:\n- \"what's the weather in nyc\" → Weather in NYC\n- \"help me write an essay about space\" → Space Essay Help\n- \"hi\" → (empty string)\n- \"debug my python code\" → Python Debugging\n\nBad outputs (never do this):\n- \"# Space Essay\" (no hashtags)\n- \"Title: Weather\" (no prefixes)\n- \"\"NYC Weather\"\" (no quotes)\n\nRules:\n- Maximum 30 characters\n- No quotes, colons, hashtags, or markdown\n- Just the topic/intent, not a full sentence", Se = 24, Ce = 8e4, we = 16e3, Te = "agent-runtime-history-compaction-summary", W = (e) => !!e && typeof e == "object" && !Array.isArray(e), G = (e) => typeof e == "string" && e.trim() ? e.trim() : null, Ee = (e) => {
58
+ let t = G((W(e.metadata) ? e.metadata : null)?.createdAt);
59
59
  if (!t) return null;
60
60
  let n = new Date(t);
61
61
  return Number.isNaN(n.getTime()) ? null : t;
62
- }, W = (e, t = 2e3) => {
62
+ }, K = (e, t = 2e3) => {
63
63
  if (typeof e == "string") return e.length > t ? `${e.slice(0, t)}...` : e;
64
64
  if (typeof e == "number" || typeof e == "boolean") return String(e);
65
65
  if (!e || typeof e != "object") return "";
@@ -70,19 +70,19 @@ ${e}`;
70
70
  return "[unserializable content]";
71
71
  }
72
72
  }, De = (e) => (Array.isArray(e.parts) ? e.parts : []).flatMap((e) => {
73
- if (!H(e)) {
74
- let t = W(e);
73
+ if (!W(e)) {
74
+ let t = K(e);
75
75
  return t ? [t] : [];
76
76
  }
77
- let t = U(e.type) ?? "part", n = W(e.text);
77
+ let t = G(e.type) ?? "part", n = K(e.text);
78
78
  if (n) return [`${t}: ${n}`];
79
- let r = W(e.output);
79
+ let r = K(e.output);
80
80
  if (r) return [`${t}: ${r}`];
81
- let i = W(e.result);
81
+ let i = K(e.result);
82
82
  if (i) return [`${t}: ${i}`];
83
- let a = W(e.content);
83
+ let a = K(e.content);
84
84
  if (a) return [`${t}: ${a}`];
85
- let o = W(e, 1e3);
85
+ let o = K(e, 1e3);
86
86
  return o ? [`${t}: ${o}`] : [];
87
87
  }).join("\n").trim(), Oe = (e) => e.reduce((e, t) => e + De(t).length, 0), ke = (e, t) => {
88
88
  if (e.length <= t) return e;
@@ -97,24 +97,24 @@ ${e}`;
97
97
  maxMessages: Se,
98
98
  maxEstimatedChars: Ce,
99
99
  maxSummaryChars: we
100
- }, G = (e) => H(e) && e.type === "agent-runtime-history-compaction" && e.version === 1 && typeof e.summary == "string", je = (e) => G(e) ? e : H(e) && G(e.historyCompaction) ? e.historyCompaction : null, Me = (e, t) => t ? H(e) && !G(e) ? {
100
+ }, je = (e) => W(e) && e.type === "agent-runtime-history-compaction" && e.version === 1 && typeof e.summary == "string", Me = (e) => je(e) ? e : W(e) && je(e.historyCompaction) ? e.historyCompaction : null, Ne = (e, t) => t ? W(e) && !je(e) ? {
101
101
  ...e,
102
102
  historyCompaction: t
103
- } : { historyCompaction: t } : e ?? null, Ne = (e) => U(e.id), Pe = (e, t) => {
104
- let n = U(t?.compactedThroughMessageId);
105
- return n ? e.findIndex((e) => Ne(e) === n) : -1;
106
- }, Fe = (e, t) => {
103
+ } : { historyCompaction: t } : e ?? null, Pe = (e) => G(e.id), Fe = (e, t) => {
104
+ let n = G(t?.compactedThroughMessageId);
105
+ return n ? e.findIndex((e) => Pe(e) === n) : -1;
106
+ }, Ie = (e, t) => {
107
107
  let n = Math.max(1, t.maxMessages), r = Math.max(1, Math.min(e.length, Math.ceil(n / 3))), i = Math.max(0, e.length - n);
108
108
  for (; i < e.length - r && Oe(e.slice(i)) > t.maxEstimatedChars;) i += 1;
109
109
  return i;
110
- }, Ie = (e) => {
111
- let t = U(e.role) ?? "message", n = Ee(e), r = De(e);
110
+ }, Le = (e) => {
111
+ let t = G(e.role) ?? "message", n = Ee(e), r = De(e);
112
112
  return `${n ? `${t} (${n})` : t}:\n${r || "[non-text content]"}`;
113
- }, Le = ({ previousContext: e, messagesToCompact: t, limits: n }) => {
114
- let r = e?.summary?.trim(), i = t.map(Ie).join("\n\n").trim();
113
+ }, Re = ({ previousContext: e, messagesToCompact: t, limits: n }) => {
114
+ let r = e?.summary?.trim(), i = t.map(Le).join("\n\n").trim();
115
115
  return ke([r ? `Earlier summary:\n${r}` : null, i ? `Compacted transcript:\n${i}` : null].filter((e) => !!e).join("\n\n"), n.maxSummaryChars).trim();
116
- }, Re = (e) => ({
117
- id: `${Te}:${U(e.compactedThroughMessageId) ?? "unknown"}`,
116
+ }, ze = (e) => ({
117
+ id: `${Te}:${G(e.compactedThroughMessageId) ?? "unknown"}`,
118
118
  role: "user",
119
119
  parts: [{
120
120
  type: "text",
@@ -130,60 +130,60 @@ ${e}`;
130
130
  transient: !0,
131
131
  historyCompaction: !0
132
132
  }
133
- }), K = (e, t) => t?.summary.trim() ? [Re(t), ...e] : e, ze = ({ messages: e, previousContext: t, limits: n }) => {
134
- let r = Pe(e, t), i = r >= 0 ? e.slice(r + 1) : e;
133
+ }), Be = (e, t) => t?.summary.trim() ? [ze(t), ...e] : e, Ve = ({ messages: e, previousContext: t, limits: n }) => {
134
+ let r = Fe(e, t), i = r >= 0 ? e.slice(r + 1) : e;
135
135
  if (!(i.length > n.maxMessages || Oe(i) > n.maxEstimatedChars)) return {
136
- messages: K(i, t),
136
+ messages: Be(i, t),
137
137
  context: t
138
138
  };
139
- let a = Fe(i, n);
139
+ let a = Ie(i, n);
140
140
  if (a <= 0) return {
141
- messages: K(i, t),
141
+ messages: Be(i, t),
142
142
  context: t
143
143
  };
144
144
  let o = i.slice(0, a), s = i.slice(a), c = o.at(-1) ?? null, l = {
145
145
  type: "agent-runtime-history-compaction",
146
146
  version: 1,
147
- summary: Le({
147
+ summary: Re({
148
148
  previousContext: t,
149
149
  messagesToCompact: o,
150
150
  limits: n
151
151
  }),
152
- compactedThroughMessageId: c ? Ne(c) : t?.compactedThroughMessageId ?? null,
152
+ compactedThroughMessageId: c ? Pe(c) : t?.compactedThroughMessageId ?? null,
153
153
  compactedThroughMessageCreatedAt: c ? Ee(c) : t?.compactedThroughMessageCreatedAt ?? null,
154
154
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
155
155
  messageCount: e.length
156
156
  };
157
157
  return {
158
- messages: K(s, l),
158
+ messages: Be(s, l),
159
159
  context: l
160
160
  };
161
- }, Be = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a, messages: o, lastContext: s }) => {
162
- let c = r().historyCompaction;
161
+ }, He = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: r, mode: i, messages: o, lastContext: s }) => {
162
+ let c = a().historyCompaction;
163
163
  if (c === !1 || c && c.enabled === !1) return {
164
164
  messages: o,
165
165
  lastContext: s ?? null,
166
166
  lastContextChanged: !1
167
167
  };
168
- let l = Ae(c), u = je(s);
168
+ let l = Ae(c), u = Me(s);
169
169
  try {
170
- let r = typeof c == "object" && typeof c.compact == "function" ? await c.compact({
170
+ let a = typeof c == "object" && typeof c.compact == "function" ? await c.compact({
171
171
  ctx: e,
172
172
  chatId: t,
173
173
  agent: n,
174
- selectedChatModel: i,
175
- mode: a,
174
+ selectedChatModel: r,
175
+ mode: i,
176
176
  messages: o,
177
177
  previousContext: u,
178
178
  limits: l
179
- }) : ze({
179
+ }) : Ve({
180
180
  messages: o,
181
181
  previousContext: u,
182
182
  limits: l
183
- }), d = Array.isArray(r.messages) ? r.messages : o, f = r.context === void 0 ? u : r.context;
183
+ }), d = Array.isArray(a.messages) ? a.messages : o, f = a.context === void 0 ? u : a.context;
184
184
  return {
185
185
  messages: d,
186
- lastContext: Me(s, f ?? null),
186
+ lastContext: Ne(s, f ?? null),
187
187
  lastContextChanged: f !== u
188
188
  };
189
189
  } catch (e) {
@@ -193,12 +193,19 @@ ${e}`;
193
193
  lastContextChanged: !1
194
194
  };
195
195
  }
196
- }, q = [
196
+ }, Ue = [
197
197
  "text",
198
198
  "code",
199
199
  "sheet"
200
- ], Ve = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, J = () => !Ve(process.env.AGENT_SDK_LIVE_TOOLS) && (Ve(process.env.PLAYWRIGHT) || process.env.NODE_ENV === "test"), He = async ({ system: e, prompt: t, dataStream: n, providerOptions: r }) => {
201
- if (J()) {
200
+ ], We = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, q = () => !We(process.env.AGENT_SDK_LIVE_TOOLS) && (We(process.env.PLAYWRIGHT) || process.env.NODE_ENV === "test"), Ge = (e) => !!(e && typeof e == "object" && !Array.isArray(e)), J = (e) => e instanceof Error ? {
201
+ errorName: e.name,
202
+ errorMessage: e.message,
203
+ errorStack: e.stack,
204
+ errorCause: e.cause
205
+ } : { errorValue: e }, Y = (e, t) => {
206
+ console.error(`[agents-sdk:getWeather] ${e}`, t);
207
+ }, Ke = async ({ system: e, prompt: t, dataStream: n, providerOptions: r }) => {
208
+ if (q()) {
202
209
  let e = `Stub document: ${t}`;
203
210
  return n.write({
204
211
  type: "data-textDelta",
@@ -206,10 +213,10 @@ ${e}`;
206
213
  transient: !0
207
214
  }), e;
208
215
  }
209
- let i = "", { fullStream: a } = S({
210
- model: R(),
216
+ let i = "", { fullStream: a } = ie({
217
+ model: B(),
211
218
  system: e,
212
- experimental_transform: ae({ chunking: "word" }),
219
+ experimental_transform: T({ chunking: "word" }),
213
220
  prompt: t,
214
221
  providerOptions: r
215
222
  });
@@ -219,8 +226,8 @@ ${e}`;
219
226
  transient: !0
220
227
  }));
221
228
  return i;
222
- }, Ue = async ({ system: e, prompt: t, dataStream: n }) => {
223
- if (J()) {
229
+ }, qe = async ({ system: e, prompt: t, dataStream: n }) => {
230
+ if (q()) {
224
231
  let e = `print("Stub code for: ${t}")\n`;
225
232
  return n.write({
226
233
  type: "data-codeDelta",
@@ -228,11 +235,11 @@ ${e}`;
228
235
  transient: !0
229
236
  }), e;
230
237
  }
231
- let r = "", { fullStream: i } = x({
232
- model: R(),
238
+ let r = "", { fullStream: i } = E({
239
+ model: B(),
233
240
  system: e,
234
241
  prompt: t,
235
- schema: A.object({ code: A.string() })
242
+ schema: P.object({ code: P.string() })
236
243
  });
237
244
  for await (let e of i) {
238
245
  if (e.type !== "object") continue;
@@ -244,8 +251,8 @@ ${e}`;
244
251
  }), r = t);
245
252
  }
246
253
  return r;
247
- }, We = async ({ system: e, prompt: t, dataStream: n }) => {
248
- if (J()) {
254
+ }, Je = async ({ system: e, prompt: t, dataStream: n }) => {
255
+ if (q()) {
249
256
  let e = `name,value\n${t.replaceAll(",", " ")},1\n`;
250
257
  return n.write({
251
258
  type: "data-sheetDelta",
@@ -253,11 +260,11 @@ ${e}`;
253
260
  transient: !0
254
261
  }), e;
255
262
  }
256
- let r = "", { fullStream: i } = x({
257
- model: R(),
263
+ let r = "", { fullStream: i } = E({
264
+ model: B(),
258
265
  system: e,
259
266
  prompt: t,
260
- schema: A.object({ csv: A.string().describe("CSV data") })
267
+ schema: P.object({ csv: P.string().describe("CSV data") })
261
268
  });
262
269
  for await (let e of i) {
263
270
  if (e.type !== "object") continue;
@@ -273,51 +280,107 @@ ${e}`;
273
280
  data: r,
274
281
  transient: !0
275
282
  }), r;
276
- }, Ge = async (e) => {
283
+ }, Ye = async (e) => {
284
+ let t = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(e)}&count=1&language=en&format=json`;
277
285
  try {
278
- let t = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(e)}&count=1&language=en&format=json`);
279
- if (!t.ok) return null;
280
- let n = await t.json();
281
- if (!n.results || n.results.length === 0) return null;
282
- let r = n.results[0];
283
- return {
284
- latitude: r.latitude,
285
- longitude: r.longitude
286
+ let n = await fetch(t);
287
+ if (!n.ok) return Y("Geocoding request failed.", {
288
+ city: e,
289
+ status: n.status,
290
+ statusText: n.statusText
291
+ }), null;
292
+ let r = await n.json().catch((t) => (Y("Geocoding response parse failed.", {
293
+ city: e,
294
+ ...J(t)
295
+ }), null)), i = Ge(r) && Array.isArray(r.results) ? r.results : [];
296
+ if (i.length === 0) return Y("Geocoding returned no results.", { city: e }), null;
297
+ let a = i[0];
298
+ if (!Ge(a)) return Y("Geocoding returned an invalid result shape.", {
299
+ city: e,
300
+ result: a
301
+ }), null;
302
+ let o = a.latitude, s = a.longitude;
303
+ return typeof o != "number" || typeof s != "number" ? (Y("Geocoding result did not include numeric coordinates.", {
304
+ city: e,
305
+ latitude: o,
306
+ longitude: s
307
+ }), null) : {
308
+ latitude: o,
309
+ longitude: s
286
310
  };
287
- } catch {
288
- return null;
311
+ } catch (t) {
312
+ return Y("Geocoding request threw.", {
313
+ city: e,
314
+ ...J(t)
315
+ }), null;
289
316
  }
290
- }, Ke = ({ ctx: e, dataStream: t, requestHints: n }) => {
291
- let r = i(e), a = async (t) => {
292
- let n = await h(e, t);
317
+ }, Xe = ({ ctx: e, dataStream: t, requestHints: n }) => {
318
+ let r = o(e), i = (t) => ({
319
+ input: t,
320
+ requestHints: n,
321
+ tenantId: r.tenantId,
322
+ userId: r.userId,
323
+ route: e.req?.path ?? e.req?.originalUrl ?? e.req?.url
324
+ }), a = async (t) => {
325
+ let n = await _(e, t);
293
326
  return n.length > 0 ? n.at(-1) ?? null : null;
294
- }, o = C({
295
- description: "Get the current weather at a location. You can provide either coordinates or a city name.",
296
- inputSchema: A.object({
297
- latitude: A.number().optional(),
298
- longitude: A.number().optional(),
299
- city: A.string().describe("City name (e.g., 'San Francisco', 'New York', 'London')").optional()
327
+ }, s = D({
328
+ description: "Get the current weather at a location. Use this for direct weather or forecast requests. You can provide either coordinates or a city name.",
329
+ inputSchema: P.object({
330
+ latitude: P.number().optional(),
331
+ longitude: P.number().optional(),
332
+ city: P.string().describe("City name (e.g., 'San Francisco', 'New York', 'London')").optional()
300
333
  }),
301
334
  needsApproval: !0,
302
335
  execute: async (e) => {
303
336
  let t, n;
304
337
  if (e.city) {
305
- let r = await Ge(e.city);
306
- if (!r) return { error: `Could not find coordinates for "${e.city}". Please check the city name.` };
338
+ let r = await Ye(e.city);
339
+ if (!r) return Y("Tool returned an error because city geocoding failed.", {
340
+ ...i(e),
341
+ city: e.city
342
+ }), { error: `Could not find coordinates for "${e.city}". Please check the city name.` };
307
343
  t = r.latitude, n = r.longitude;
308
344
  } else if (e.latitude !== void 0 && e.longitude !== void 0) t = e.latitude, n = e.longitude;
309
- else return { error: "Please provide either a city name or both latitude and longitude coordinates." };
310
- let r = await (await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${t}&longitude=${n}&current=temperature_2m&hourly=temperature_2m&daily=sunrise,sunset&timezone=auto`)).json();
311
- return "city" in e && (r.cityName = e.city), r;
345
+ else return Y("Tool returned an error because location input was missing.", { ...i(e) }), { error: "Please provide either a city name or both latitude and longitude coordinates." };
346
+ try {
347
+ let r = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${t}&longitude=${n}&current=temperature_2m&hourly=temperature_2m&daily=sunrise,sunset&timezone=auto`);
348
+ if (!r.ok) return Y("Forecast request failed.", {
349
+ ...i(e),
350
+ latitude: t,
351
+ longitude: n,
352
+ status: r.status,
353
+ statusText: r.statusText
354
+ }), { error: "Weather lookup failed. Please try again." };
355
+ let a = await r.json().catch((r) => (Y("Forecast response parse failed.", {
356
+ ...i(e),
357
+ latitude: t,
358
+ longitude: n,
359
+ ...J(r)
360
+ }), null));
361
+ return Ge(a) ? ("city" in e && (a.cityName = e.city), a) : (Y("Tool returned an error because forecast response was invalid.", {
362
+ ...i(e),
363
+ latitude: t,
364
+ longitude: n,
365
+ weatherData: a
366
+ }), { error: "Weather lookup failed. Please try again." });
367
+ } catch (r) {
368
+ return Y("Forecast request threw.", {
369
+ ...i(e),
370
+ latitude: t,
371
+ longitude: n,
372
+ ...J(r)
373
+ }), { error: "Weather lookup failed. Please try again." };
374
+ }
312
375
  }
313
- }), s = C({
376
+ }), l = D({
314
377
  description: "Create an artifact for writing or content creation. Use kind 'code' for programming, 'text' for writing, and 'sheet' for spreadsheets or tabular data.",
315
- inputSchema: A.object({
316
- title: A.string().describe("The title of the artifact"),
317
- kind: A.enum(q).describe("Use 'code' for programming, 'text' for prose, and 'sheet' for CSV/tabular data")
378
+ inputSchema: P.object({
379
+ title: P.string().describe("The title of the artifact"),
380
+ kind: P.enum(Ue).describe("Use 'code' for programming, 'text' for prose, and 'sheet' for CSV/tabular data")
318
381
  }),
319
382
  execute: async ({ title: n, kind: r }) => {
320
- let i = D();
383
+ let i = A();
321
384
  t.write({
322
385
  type: "data-kind",
323
386
  data: r,
@@ -336,19 +399,19 @@ ${e}`;
336
399
  transient: !0
337
400
  });
338
401
  let a = "";
339
- return r === "text" ? a = await He({
402
+ return r === "text" ? a = await Ke({
340
403
  system: "Write about the given topic. Markdown is supported. Use headings wherever appropriate.",
341
404
  prompt: n,
342
405
  dataStream: t
343
- }) : r === "code" ? a = await Ue({
406
+ }) : r === "code" ? a = await qe({
344
407
  system: ve,
345
408
  prompt: n,
346
409
  dataStream: t
347
- }) : r === "sheet" && (a = await We({
410
+ }) : r === "sheet" && (a = await Je({
348
411
  system: ye,
349
412
  prompt: n,
350
413
  dataStream: t
351
- })), await f(e, {
414
+ })), await p(e, {
352
415
  id: i,
353
416
  title: n,
354
417
  kind: r,
@@ -364,24 +427,24 @@ ${e}`;
364
427
  content: r === "code" ? "A script was created and is now visible to the user." : "A document was created and is now visible to the user."
365
428
  };
366
429
  }
367
- }), c = C({
430
+ }), u = D({
368
431
  description: "Fully rewrite an existing artifact with the given description. Use editDocument instead for targeted find-and-replace changes.",
369
- inputSchema: A.object({
370
- id: A.string().describe("The ID of the artifact to rewrite"),
371
- description: A.string().default("Improve the content").describe("The description of changes that need to be made")
432
+ inputSchema: P.object({
433
+ id: P.string().describe("The ID of the artifact to rewrite"),
434
+ description: P.string().default("Improve the content").describe("The description of changes that need to be made")
372
435
  }),
373
436
  execute: async ({ id: n, description: r }) => {
374
437
  let i = await a(n);
375
438
  if (!i) return { error: "Document not found" };
376
439
  let o = i.kind;
377
- if (!q.includes(o)) return { error: `Unsupported document kind: ${i.kind}` };
440
+ if (!Ue.includes(o)) return { error: `Unsupported document kind: ${i.kind}` };
378
441
  t.write({
379
442
  type: "data-clear",
380
443
  data: null,
381
444
  transient: !0
382
445
  });
383
446
  let s = "";
384
- return o === "text" ? s = await He({
447
+ return o === "text" ? s = await Ke({
385
448
  system: be(i.content, i.kind),
386
449
  prompt: r,
387
450
  dataStream: t,
@@ -389,15 +452,15 @@ ${e}`;
389
452
  type: "content",
390
453
  content: i.content
391
454
  } } }
392
- }) : o === "code" ? s = await Ue({
455
+ }) : o === "code" ? s = await qe({
393
456
  system: be(i.content, i.kind),
394
457
  prompt: r,
395
458
  dataStream: t
396
- }) : o === "sheet" && (s = await We({
459
+ }) : o === "sheet" && (s = await Je({
397
460
  system: be(i.content, i.kind),
398
461
  prompt: r,
399
462
  dataStream: t
400
- })), await f(e, {
463
+ })), await p(e, {
401
464
  id: i.id,
402
465
  title: i.title,
403
466
  kind: i.kind,
@@ -415,25 +478,25 @@ ${e}`;
415
478
  }
416
479
  });
417
480
  return {
418
- getWeather: o,
419
- createDocument: s,
420
- editDocument: C({
481
+ getWeather: s,
482
+ createDocument: l,
483
+ editDocument: D({
421
484
  description: "Make a targeted edit to an existing artifact by replacing an exact string. Prefer this over updateDocument for small changes, fixes, renames, and isolated edits.",
422
- inputSchema: A.object({
423
- id: A.string().describe("The ID of the artifact to edit"),
424
- old_string: A.string().min(1).describe("Exact string to find. Include enough surrounding context to make the match unique."),
425
- new_string: A.string().describe("Replacement string"),
426
- replace_all: A.boolean().optional().describe("Replace all occurrences instead of only the first one")
485
+ inputSchema: P.object({
486
+ id: P.string().describe("The ID of the artifact to edit"),
487
+ old_string: P.string().min(1).describe("Exact string to find. Include enough surrounding context to make the match unique."),
488
+ new_string: P.string().describe("Replacement string"),
489
+ replace_all: P.boolean().optional().describe("Replace all occurrences instead of only the first one")
427
490
  }),
428
491
  execute: async ({ id: n, old_string: r, new_string: i, replace_all: o }) => {
429
492
  let s = await a(n);
430
493
  if (!s) return { error: "Document not found" };
431
494
  if (!s.content) return { error: "Document has no content" };
432
495
  let c = s.kind;
433
- if (!q.includes(c)) return { error: `Unsupported document kind: ${s.kind}` };
496
+ if (!Ue.includes(c)) return { error: `Unsupported document kind: ${s.kind}` };
434
497
  if (!s.content.includes(r)) return { error: "old_string not found in document" };
435
498
  let l = o ? s.content.replaceAll(r, i) : s.content.replace(r, i);
436
- return await f(e, {
499
+ return await p(e, {
437
500
  id: s.id,
438
501
  title: s.title,
439
502
  kind: s.kind,
@@ -466,19 +529,19 @@ ${e}`;
466
529
  };
467
530
  }
468
531
  }),
469
- updateDocument: c,
470
- requestSuggestions: C({
532
+ updateDocument: u,
533
+ requestSuggestions: D({
471
534
  description: "Request writing suggestions for an existing document artifact. Only use this when the user explicitly asks to improve or get suggestions for a document they have already created. Never use for general questions.",
472
- inputSchema: A.object({ documentId: A.string().describe("The UUID of an existing document artifact that was previously created with createDocument") }),
535
+ inputSchema: P.object({ documentId: P.string().describe("The UUID of an existing document artifact that was previously created with createDocument") }),
473
536
  execute: async ({ documentId: n }) => {
474
537
  let i = await a(n);
475
538
  if (!i?.content) return { error: "Document not found" };
476
- if (J()) {
539
+ if (q()) {
477
540
  let a = {
478
541
  originalText: "Stub original sentence.",
479
542
  suggestedText: "Stub suggested sentence.",
480
543
  description: "Stub suggestion",
481
- id: D(),
544
+ id: A(),
482
545
  documentId: n,
483
546
  documentCreatedAt: i.createdAt,
484
547
  isResolved: !1,
@@ -489,7 +552,7 @@ ${e}`;
489
552
  type: "data-suggestion",
490
553
  data: a,
491
554
  transient: !0
492
- }), await l(e, {
555
+ }), await c(e, {
493
556
  documentId: n,
494
557
  suggestions: [a]
495
558
  }), {
@@ -499,24 +562,24 @@ ${e}`;
499
562
  message: "Suggestions have been added to the document"
500
563
  };
501
564
  }
502
- let o = [], { partialOutputStream: s } = S({
503
- model: R(),
565
+ let o = [], { partialOutputStream: s } = ie({
566
+ model: B(),
504
567
  system: "You are a help writing assistant. Given a piece of writing, please offer suggestions to improve the piece of writing and describe the change. It is very important for the edits to contain full sentences instead of just words. Max 5 suggestions.",
505
568
  prompt: i.content,
506
- output: b.array({ element: A.object({
507
- originalSentence: A.string().describe("The original sentence"),
508
- suggestedSentence: A.string().describe("The suggested sentence"),
509
- description: A.string().describe("The description of the suggestion")
569
+ output: C.array({ element: P.object({
570
+ originalSentence: P.string().describe("The original sentence"),
571
+ suggestedSentence: P.string().describe("The suggested sentence"),
572
+ description: P.string().describe("The description of the suggestion")
510
573
  }) })
511
- }), c = 0;
512
- for await (let e of s) if (e) for (let a = c; a < e.length; a++) {
574
+ }), l = 0;
575
+ for await (let e of s) if (e) for (let a = l; a < e.length; a++) {
513
576
  let s = e[a];
514
577
  if (!s?.originalSentence || !s?.suggestedSentence || !s?.description) continue;
515
- let l = {
578
+ let c = {
516
579
  originalText: s.originalSentence,
517
580
  suggestedText: s.suggestedSentence,
518
581
  description: s.description,
519
- id: D(),
582
+ id: A(),
520
583
  documentId: n,
521
584
  documentCreatedAt: i.createdAt,
522
585
  isResolved: !1,
@@ -525,11 +588,11 @@ ${e}`;
525
588
  };
526
589
  t.write({
527
590
  type: "data-suggestion",
528
- data: l,
591
+ data: c,
529
592
  transient: !0
530
- }), o.push(l), c++;
593
+ }), o.push(c), l++;
531
594
  }
532
- return o.length > 0 && await l(e, {
595
+ return o.length > 0 && await c(e, {
533
596
  documentId: n,
534
597
  suggestions: o
535
598
  }), {
@@ -540,7 +603,7 @@ ${e}`;
540
603
  };
541
604
  }
542
605
  }),
543
- webSearch: k.tools.webSearch({
606
+ webSearch: N.tools.webSearch({
544
607
  externalWebAccess: !0,
545
608
  searchContextSize: "medium",
546
609
  userLocation: {
@@ -550,48 +613,65 @@ ${e}`;
550
613
  }
551
614
  })
552
615
  };
553
- }, qe = (e) => e ? !e.trim() : !0, Je = (e) => (Array.isArray(e) ? e : []).filter((e) => !!e && typeof e == "object" && !!e && "type" in e && "text" in e && e.type === "text" && typeof e.text == "string").map((e) => e.text).join("").trim(), Ye = (e) => {
616
+ }, Ze = "getWeather", Qe = "webSearch", $e = (e) => e.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase(), et = [
617
+ /\bweather\b/,
618
+ /\bforecast\b/,
619
+ /\btemperatures?\b/,
620
+ /\bmeteo\b/,
621
+ /\bquel temps\b/,
622
+ /\btemps fait\b/,
623
+ /\bil fait\b.*\b(temps|froid|chaud|beau|mauvais)\b/,
624
+ /\bpleut\b/,
625
+ /\bpluie\b/
626
+ ], tt = (e) => {
627
+ let t = $e(e);
628
+ return t ? et.some((e) => e.test(t)) : !1;
629
+ }, nt = ({ activeTools: e, availableTools: t, userText: n }) => {
630
+ let r = Ze in t, i = e.includes(Ze), a = e.includes(Qe);
631
+ return !r || !i || !a || !tt(n) ? [...e] : e.filter((e) => e !== Qe);
632
+ }, rt = (e) => e ? !e.trim() : !0, it = (e) => (Array.isArray(e) ? e : []).filter((e) => !!e && typeof e == "object" && !!e && "type" in e && "text" in e && e.type === "text" && typeof e.text == "string").map((e) => e.text).join("").trim(), at = (e) => {
554
633
  let t = e.trim();
555
634
  return t = t.replaceAll("\n", " "), t = t.replaceAll("\r", " "), t = t.replace(/\s+/g, " ").trim(), t = t.replace(/^(?:chat\s+)?title\s*[:\-–—]\s*/i, ""), t = t.replace(/^[#*\-•>"'`\s]+/, ""), t = t.replace(/[#:]/g, " "), t = t.replace(/[`"'*_~[\]()\\]/g, ""), t = t.replace(/\s+/g, " ").trim(), t.length > 30 && (t = t.slice(0, 30).trimEnd()), t;
556
- }, Xe = (e) => {
635
+ }, ot = (e) => {
557
636
  let t = e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").replace(/\s+/g, " ").trim();
558
637
  return t === "hi" || t === "hello" || t === "hey" || t === "salut" || t === "bonjour";
559
- }, Y = (e) => {
638
+ }, st = (e) => {
560
639
  let t = e.trim();
561
- return !t || Xe(t) ? "" : Ye(t.replaceAll("\n", " ").replaceAll("\r", " ").split(/\s+/).filter((e) => e.trim() !== "").slice(0, 5).join(" "));
562
- }, Ze = "/api/rb/agents/chat";
563
- A.any(), A.any();
564
- //#endregion
565
- //#region src/api/chat/handler.ts
566
- var Qe = /* @__PURE__ */ e({
567
- default: () => zt,
568
- runAgentLoop: () => $
569
- }), $e = 1024 * 1024 * 20, et = 1e5, tt = /^\/api\/rb\/files\/([^/]+)\/?$/, nt = "test-model", rt = "openai/gpt-5.4-mini", it = async (e) => new Promise((t) => setTimeout(t, e)), at = async (e, t) => {
570
- let n = v(t);
571
- n && !n.isDone || await c(e, {
640
+ return !t || ot(t) ? "" : at(t.replaceAll("\n", " ").replaceAll("\r", " ").split(/\s+/).filter((e) => e.trim() !== "").slice(0, 5).join(" "));
641
+ }, ct = "/api/rb/agents/chat";
642
+ P.any(), P.any();
643
+ var lt = 1024 * 1024 * 20, ut = 1e5, dt = /^\/api\/rb\/files\/([^/]+)\/?$/, ft = "test-model", pt = "openai/gpt-5.4-mini", mt = 9e3, ht = new Set([
644
+ "start",
645
+ "start-step",
646
+ "finish-step",
647
+ "finish",
648
+ "raw"
649
+ ]), gt = async (e) => new Promise((t) => setTimeout(t, e)), _t = async (e, t) => {
650
+ let n = x(t);
651
+ n && !n.isDone || await y(e, {
572
652
  chatId: t,
573
653
  isStreaming: !1
574
654
  });
575
- }, ot = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, X = (e) => typeof e == "string" && e.trim() || null, st = () => {
576
- let e = r().chatModels;
577
- if (!e?.length) return F;
655
+ }, vt = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, X = (e) => typeof e == "string" && e.trim() || null, yt = () => {
656
+ let e = a().chatModels;
657
+ if (!e?.length) return L;
578
658
  let t = /* @__PURE__ */ new Set();
579
659
  for (let n of e) {
580
660
  let e = X(typeof n == "string" ? n : n.id);
581
661
  e && t.add(e);
582
662
  }
583
663
  return t;
584
- }, ct = (e) => {
664
+ }, bt = (e) => {
585
665
  if (typeof e == "boolean") return e;
586
666
  let t = X(e)?.toLowerCase();
587
667
  return t ? t === "true" ? !0 : t === "false" ? !1 : null : null;
588
- }, lt = (e) => {
668
+ }, xt = (e) => {
589
669
  let t = e.req?.session?.user?.currentTenantId;
590
670
  return X(t);
591
- }, ut = (e) => {
671
+ }, St = (e) => {
592
672
  let t = e.req?.session?.user?.id;
593
673
  return X(t);
594
- }, dt = () => X(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", ft = (e) => E("sha256").update(Buffer.from(e)).digest("hex"), pt = (e) => {
674
+ }, Ct = () => X(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", wt = (e) => ae("sha256").update(Buffer.from(e)).digest("hex"), Tt = (e) => {
595
675
  let t = e.trim();
596
676
  if (!t) return null;
597
677
  let n;
@@ -604,36 +684,36 @@ var Qe = /* @__PURE__ */ e({
604
684
  return null;
605
685
  }
606
686
  }
607
- let r = tt.exec(n.pathname);
687
+ let r = dt.exec(n.pathname);
608
688
  if (!r) return null;
609
689
  let i = X(decodeURIComponent(r[1]));
610
690
  return i ? {
611
691
  fileId: i,
612
692
  uploadKey: X(n.searchParams.get("rb-upload-key"))
613
693
  } : null;
614
- }, mt = async ({ ctx: e, fileId: t, uploadKey: n }) => {
615
- let r = lt(e);
694
+ }, Et = async ({ ctx: e, fileId: t, uploadKey: n }) => {
695
+ let r = xt(e);
616
696
  if (!r) throw Error("tenant_missing");
617
697
  let i;
618
698
  try {
619
- i = new O(t);
699
+ i = new oe(t);
620
700
  } catch {
621
701
  throw Error("invalid_file_id");
622
702
  }
623
- let a = (await T(r)).db;
703
+ let a = (await k(r)).db;
624
704
  if (!a) throw Error("filesystem_db_unavailable");
625
- let o = new se(a, { bucketName: dt() }), [s] = await o.find({ _id: i }).limit(1).toArray();
705
+ let o = new j(a, { bucketName: Ct() }), [s] = await o.find({ _id: i }).limit(1).toArray();
626
706
  if (!s) throw Error("file_not_found");
627
- let c = ct(s?.metadata?.isPublic) ?? !1, l = ut(e), u = X(s?.metadata?.userId), d = X(s?.metadata?.ownerKeyHash);
707
+ let c = bt(s?.metadata?.isPublic) ?? !1, l = St(e), u = X(s?.metadata?.userId), d = X(s?.metadata?.ownerKeyHash);
628
708
  if (!c) {
629
- let e = !!(l && u && l === u), t = !!(n && d && ft(n) === d);
709
+ let e = !!(l && u && l === u), t = !!(n && d && wt(n) === d);
630
710
  if (!e && !t) throw Error("unauthorized");
631
711
  }
632
712
  let f = X(s?.metadata?.mimeType), p = [], m = 0;
633
713
  return await new Promise((e, t) => {
634
714
  let n = o.openDownloadStream(i);
635
715
  n.on("data", (e) => {
636
- if (m += e.length, m > $e) {
716
+ if (m += e.length, m > lt) {
637
717
  n.destroy(/* @__PURE__ */ Error("attachment_too_large"));
638
718
  return;
639
719
  }
@@ -643,16 +723,16 @@ var Qe = /* @__PURE__ */ e({
643
723
  data: Buffer.concat(p, m),
644
724
  mimeType: f
645
725
  };
646
- }, ht = async (e, t) => {
726
+ }, Dt = async (e, t) => {
647
727
  let n = Array.isArray(t) ? t : [], r = [];
648
728
  for (let t of n) {
649
729
  if (!t || typeof t != "object" || !("role" in t) || t.role !== "user") continue;
650
730
  let n = Array.isArray(t.content) ? t.content : null;
651
731
  if (n) for (let t of n) {
652
732
  if (!t || typeof t != "object" || t.type !== "file" || typeof t.data != "string") continue;
653
- let n = pt(t.data);
733
+ let n = Tt(t.data);
654
734
  n && r.push((async () => {
655
- let { data: r, mimeType: i } = await mt({
735
+ let { data: r, mimeType: i } = await Et({
656
736
  ctx: e,
657
737
  ...n
658
738
  });
@@ -661,7 +741,7 @@ var Qe = /* @__PURE__ */ e({
661
741
  }
662
742
  }
663
743
  r.length > 0 && await Promise.all(r);
664
- }, gt = (e) => {
744
+ }, Ot = (e) => {
665
745
  let t = Array.isArray(e) ? e : [];
666
746
  for (let e of t) {
667
747
  if (!e || typeof e != "object" || !("role" in e) || e.role !== "user") continue;
@@ -674,7 +754,7 @@ var Qe = /* @__PURE__ */ e({
674
754
  let i = X(n.filename) ?? X(n.name) ?? `attachment-${e + 1}`, a = n.data;
675
755
  if (r?.startsWith("text/") && a instanceof Uint8Array) {
676
756
  let n = (Buffer.isBuffer(a) ? a : Buffer.from(a)).toString("utf8");
677
- n.length > et && (n = `${n.slice(0, et)}\n\n[Truncated]`);
757
+ n.length > ut && (n = `${n.slice(0, ut)}\n\n[Truncated]`);
678
758
  let o = r === "text/csv" || i.toLowerCase().endsWith(".csv") ? "csv" : "";
679
759
  t[e] = {
680
760
  type: "text",
@@ -689,59 +769,59 @@ var Qe = /* @__PURE__ */ e({
689
769
  };
690
770
  }
691
771
  }
692
- }, _t = async (e, t, n) => {
693
- if (e.message?.role === "user") return Je(e.message.parts);
772
+ }, kt = async (e, t, n) => {
773
+ if (e.message?.role === "user") return it(e.message.parts);
694
774
  if (Array.isArray(e.messages)) {
695
775
  let t = null;
696
776
  for (let n = e.messages.length - 1; n >= 0; --n) {
697
777
  let r = e.messages[n];
698
778
  if (r?.role !== "user") continue;
699
- let i = Je(r.parts);
779
+ let i = it(r.parts);
700
780
  if (i) {
701
- if (Y(i)) return i;
781
+ if (st(i)) return i;
702
782
  t ??= i;
703
783
  }
704
784
  }
705
785
  if (t) return t;
706
786
  }
707
- let r = await d(t, n), i = null;
787
+ let r = await m(t, n), i = null;
708
788
  for (let e = r.length - 1; e >= 0; --e) {
709
789
  let t = r[e];
710
790
  if (t.role !== "user") continue;
711
- let n = Je(t.parts);
791
+ let n = it(t.parts);
712
792
  if (n) {
713
- if (Y(n)) return n;
793
+ if (st(n)) return n;
714
794
  i ??= n;
715
795
  }
716
796
  }
717
797
  return i ?? "";
718
- }, vt = (e) => {
798
+ }, At = (e) => {
719
799
  let t = Array.isArray(e.messages) && e.messages.length > 0 ? e.messages.at(-1) : e.message;
720
800
  return !t || t.role !== "user" ? "" : (Array.isArray(t.parts) ? t.parts : []).filter((e) => !!e && typeof e == "object" && !!e && "type" in e && "text" in e && e.type === "text" && typeof e.text == "string").map((e) => e.text).join("\n").trim();
721
- }, yt = (e) => {
801
+ }, jt = (e) => {
722
802
  let t = e.id;
723
803
  return typeof t == "string" && t.trim() !== "" ? t : null;
724
- }, bt = (e) => {
804
+ }, Mt = (e) => {
725
805
  let t = e.selectedChatModel;
726
806
  return typeof t == "string" && t.trim() !== "" ? t : null;
727
- }, xt = (e) => {
807
+ }, Nt = (e) => {
728
808
  let t = e.openaiReasoningEffort;
729
809
  return typeof t == "string" && t.trim() !== "" ? t.trim() : null;
730
- }, St = (e) => {
810
+ }, Pt = (e) => {
731
811
  if (!e || typeof e != "object") return !1;
732
812
  let t = e.state, n = e.toolCallId;
733
813
  return typeof n == "string" && n.trim() !== "" && (t === "approval-responded" || t === "output-denied");
734
- }, Ct = (e) => {
814
+ }, Ft = (e) => {
735
815
  let t = Array.isArray(e.messages) ? e.messages : [];
736
- return t.length === 0 || t.at(-1)?.role === "user" ? !1 : t.some((e) => (Array.isArray(e?.parts) ? e.parts : []).some((e) => St(e)));
737
- }, wt = (e) => {
816
+ return t.length === 0 || t.at(-1)?.role === "user" ? !1 : t.some((e) => (Array.isArray(e?.parts) ? e.parts : []).some((e) => Pt(e)));
817
+ }, It = (e) => {
738
818
  let t = /* @__PURE__ */ new Map();
739
819
  for (let n of e) {
740
820
  let e = Array.isArray(n?.parts) ? n.parts : [];
741
- for (let n of e) St(n) && t.set(n.toolCallId, n);
821
+ for (let n of e) Pt(n) && t.set(n.toolCallId, n);
742
822
  }
743
823
  return t;
744
- }, Tt = (e, t) => {
824
+ }, Lt = (e, t) => {
745
825
  let n = [];
746
826
  return {
747
827
  changedMessages: n,
@@ -764,21 +844,64 @@ var Qe = /* @__PURE__ */ e({
764
844
  return n.push(a), a;
765
845
  })
766
846
  };
767
- }, Et = (e) => {
847
+ }, Rt = (e) => {
768
848
  if (!e || typeof e != "object" || !("createdAt" in e)) return null;
769
849
  let t = e.createdAt;
770
850
  if (typeof t != "string") return null;
771
851
  let n = new Date(t);
772
852
  return Number.isNaN(n.getTime()) ? null : n;
773
- }, Dt = (e) => ({
853
+ }, zt = (e) => ({
774
854
  latitude: null,
775
855
  longitude: null,
776
856
  city: null,
777
857
  country: null
778
- }), Ot = (e) => {
858
+ }), Bt = (e) => {
779
859
  let [t] = e.split("/");
780
860
  return t && t !== e ? t : "unknown";
781
- }, Z = (e) => typeof e == "number" && Number.isFinite(e) ? e : void 0, kt = (e) => e instanceof Error && e.message.trim() ? e.message : "Unknown error", At = (e) => {
861
+ }, Vt = (e) => {
862
+ switch (Bt(e)) {
863
+ case "openai": return "OpenAI";
864
+ case "google": return "Google Gemini";
865
+ case "xai": return "xAI";
866
+ default: return "Provider";
867
+ }
868
+ }, Ht = (e) => {
869
+ switch (Bt(e)) {
870
+ case "openai": return "Set OPENAI_API_KEY and try again.";
871
+ case "google": return "Set GOOGLE_GENERATIVE_AI_API_KEY or GOOGLE_API_KEY and try again.";
872
+ case "xai": return "Set XAI_API_KEY and try again.";
873
+ default: return "Check the provider API key and try again.";
874
+ }
875
+ }, Ut = (e) => {
876
+ let t = a().chatModels ?? [];
877
+ for (let n of t) {
878
+ if (typeof n == "string") {
879
+ if (n === e) return e;
880
+ continue;
881
+ }
882
+ if (n.id !== e) continue;
883
+ let t = n.name;
884
+ return typeof t == "string" && t.trim() ? t.trim() : n.id;
885
+ }
886
+ let [, n] = e.split("/", 2);
887
+ return n || e;
888
+ }, Wt = (e) => typeof e.type == "string" ? !ht.has(e.type) : !1, Z = (e) => typeof e == "number" && Number.isFinite(e) ? e : void 0, Gt = (e) => e instanceof Error && e.message.trim() ? e.message : "Unknown error", Kt = (e, t) => {
889
+ let n = Gt(e).toLowerCase(), r = Vt(t);
890
+ return n.includes("api key") || n.includes("apikey") || n.includes("unauthorized") || n.includes("invalid authentication") || n.includes("401") ? `${r} API key is missing or invalid. ${Ht(t)}` : n.includes("quota") || n.includes("rate limit") || n.includes("rate_limit") || n.includes("billing") || n.includes("credit") || n.includes("429") ? `${r} could not process this request because of quota, rate limit, or billing limits. Check provider usage and billing, then try again.` : n.includes("tool approval") || n.includes("approvalid") || n.includes("approval id") || n.includes("tool call") || n.includes("tool result") || n.includes("missing tool") ? "The tool approval state for this message is out of date. Please retry the tool call." : n.includes("model not found") || n.includes("not found") || n.includes("unsupported model") || n.includes("404") ? `${r} could not use the selected model "${t}". Check the model configuration and provider access.` : "Something went wrong.";
891
+ }, qt = (e) => e instanceof Error ? {
892
+ errorName: e.name,
893
+ errorMessage: e.message,
894
+ errorStack: e.stack,
895
+ errorCause: e.cause
896
+ } : { errorValue: e }, Q = (e, t, n) => {
897
+ console.error(e, {
898
+ ...n,
899
+ ...qt(t)
900
+ });
901
+ }, Jt = (e) => ({
902
+ chatId: jt(e),
903
+ selectedChatModel: Mt(e)
904
+ }), Yt = (e) => {
782
905
  let t = e && typeof e == "object" ? e : {}, n = t.inputTokenDetails && typeof t.inputTokenDetails == "object" ? t.inputTokenDetails : {}, r = t.outputTokenDetails && typeof t.outputTokenDetails == "object" ? t.outputTokenDetails : {};
783
906
  return {
784
907
  inputTokens: Z(t.inputTokens),
@@ -788,63 +911,77 @@ var Qe = /* @__PURE__ */ e({
788
911
  reasoningTokens: Z(r.reasoningTokens) ?? Z(t.reasoningTokens),
789
912
  rawUsage: Object.keys(t).length > 0 ? t.raw ?? t : void 0
790
913
  };
791
- }, jt = () => ({
914
+ }, Xt = () => ({
792
915
  inputTokens: 0,
793
916
  outputTokens: 0,
794
917
  totalTokens: 0,
795
918
  cachedInputTokens: 0,
796
919
  reasoningTokens: 0
797
- }), Mt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a }) => {
920
+ }), Zt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: r, mode: i }) => {
798
921
  try {
799
- return { workspaceId: X((await r().resolveUsageContext?.({
922
+ return { workspaceId: X((await a().resolveUsageContext?.({
800
923
  ctx: e,
801
924
  chatId: t,
802
925
  agent: n,
803
- selectedChatModel: i,
804
- mode: a
926
+ selectedChatModel: r,
927
+ mode: i
805
928
  }))?.workspaceId) ?? void 0 };
806
929
  } catch (e) {
807
930
  return console.warn("Failed to resolve agent usage context.", e), { workspaceId: void 0 };
808
931
  }
809
- }, Q = async ({ ctx: e, usageContext: t, agent: n, chatId: r, mode: i, feature: a, modelId: s, status: c, billable: l, usage: u, finishReason: d, error: f, startedAt: p, finishedAt: m = /* @__PURE__ */ new Date() }) => {
810
- let h = u ? At(u) : {}, g = {
811
- id: D(),
932
+ }, Qt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: r, mode: i }) => {
933
+ let o = a().shouldGenerateChatTitle;
934
+ if (!o) return !0;
935
+ try {
936
+ return await o({
937
+ ctx: e,
938
+ chatId: t,
939
+ agent: n,
940
+ selectedChatModel: r,
941
+ mode: i
942
+ });
943
+ } catch (e) {
944
+ return console.warn("Failed to resolve chat title generation setting.", e), !0;
945
+ }
946
+ }, $ = async ({ ctx: e, usageContext: t, agent: n, chatId: r, mode: i, feature: a, modelId: o, status: s, billable: c, usage: l, finishReason: u, error: d, startedAt: f, finishedAt: p = /* @__PURE__ */ new Date() }) => {
947
+ let m = l ? Yt(l) : {}, h = {
948
+ id: A(),
812
949
  workspaceId: t.workspaceId,
813
950
  agentId: n.id,
814
951
  chatId: r,
815
952
  mode: i,
816
953
  feature: a,
817
- provider: Ot(s),
818
- model: s,
819
- billable: l,
820
- status: c,
821
- finishReason: X(d) ?? void 0,
822
- errorMessage: f ? kt(f) : void 0,
823
- ...h,
824
- startedAt: p,
825
- finishedAt: m,
954
+ provider: Bt(o),
955
+ model: o,
956
+ billable: c,
957
+ status: s,
958
+ finishReason: X(u) ?? void 0,
959
+ errorMessage: d ? Gt(d) : void 0,
960
+ ...m,
961
+ startedAt: f,
962
+ finishedAt: p,
826
963
  createdAt: /* @__PURE__ */ new Date()
827
964
  };
828
965
  try {
829
- await o(e, g);
966
+ await v(e, h);
830
967
  } catch (e) {
831
968
  console.error("Failed to save agents usage event.", e);
832
969
  }
833
- }, Nt = (e) => `agents-sdk:chat:${e}:stream`, Pt = async ({ ctx: e, chatId: t, selectedChatModel: i }) => await r().resolveAgent?.({
970
+ }, $t = (e) => `agents-sdk:chat:${e}:stream`, en = async ({ ctx: e, chatId: t, selectedChatModel: n }) => await a().resolveAgent?.({
834
971
  ctx: e,
835
972
  chatId: t,
836
- selectedChatModel: i
837
- }) ?? n(), Ft = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
838
- let a = i(e), o = Nt(t), s = y({
973
+ selectedChatModel: n
974
+ }) ?? i(), tn = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
975
+ let i = o(e), a = $t(t), s = S({
839
976
  chatId: t,
840
977
  abortWhenNoSubscribersMs: n === "headless" || r ? 0 : void 0
841
978
  });
842
979
  n === "interactive" && s.subscribe(e);
843
980
  let c = (e) => {
844
981
  r && r.publish({
845
- tenantId: a.tenantId,
846
- userId: a.userId,
847
- channel: o,
982
+ tenantId: i.tenantId,
983
+ userId: i.userId,
984
+ channel: a,
848
985
  payload: e
849
986
  });
850
987
  };
@@ -863,264 +1000,282 @@ var Qe = /* @__PURE__ */ e({
863
1000
  });
864
1001
  }
865
1002
  };
866
- }, It = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
1003
+ }, nn = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
867
1004
  if (!n) return;
868
- let a = i(e);
1005
+ let i = o(e);
869
1006
  n.publish({
870
- tenantId: a.tenantId,
871
- userId: a.userId,
872
- channel: Nt(t),
1007
+ tenantId: i.tenantId,
1008
+ userId: i.userId,
1009
+ channel: $t(t),
873
1010
  payload: {
874
1011
  chatId: t,
875
1012
  message: r
876
1013
  }
877
1014
  });
878
- }, $ = async ({ payload: e, ctx: n, mode: o = "interactive", streamTransport: l = null }) => {
879
- let f = yt(e);
880
- if (!f) return a(n, "bad_request:api", "Parameter id is required.");
881
- let p = e, h = bt(p), v = ot(process.env.PLAYWRIGHT), y = !ot(process.env.AGENT_SDK_LIVE_CHAT) && v || process.env.NODE_ENV === "test";
882
- if (!h) return a(n, "bad_request:api", "Parameter selectedChatModel is required.");
883
- if (h === nt && (y = !0), h !== nt && (!st().has(h) || !me(h))) return a(n, "bad_request:api", `Unsupported selectedChatModel: "${h}".`);
884
- let b = process.env.OPENAI_API_KEY, re = process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY, ae = process.env.XAI_API_KEY, x = ue(h), C = de(h), w = fe(h), T = xt(p), E = T && T !== "default" && T !== "off" ? T : null, se = t(h);
885
- if (E && !se.some((e) => e === E)) return a(n, "bad_request:api", `Unsupported reasoning effort "${E}" for selectedChatModel: "${h}".`);
886
- if (!y && x && !b) return a(n, "bad_request:provider", "Missing OPENAI_API_KEY.");
887
- if (!y && C && !re) return a(n, "bad_request:provider", "Missing GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY).");
888
- if (!y && w && !ae) return a(n, "bad_request:provider", "Missing XAI_API_KEY.");
889
- if (!y && !x && !C && !w) return a(n, "bad_request:provider", `Unsupported selectedChatModel: "${h}".`);
890
- let O = await Pt({
891
- ctx: n,
892
- chatId: f,
893
- selectedChatModel: h
894
- }), ce = await r().resolveKnowledge?.({
895
- ctx: n,
896
- chatId: f,
897
- agent: O,
898
- selectedChatModel: h
899
- }) ?? null, k = await Mt({
900
- ctx: n,
901
- chatId: f,
902
- agent: O,
903
- selectedChatModel: h,
904
- mode: o
905
- }), le = i(n), A = await s(n, f, { includeDeleted: !0 });
906
- if (A?.deletedAt) return a(n, "not_found:chat");
907
- A ? A.selectedChatModel !== h && await ee(n, {
908
- chatId: f,
909
- selectedChatModel: h
910
- }) : await m(n, {
911
- id: f,
1015
+ }, rn = async ({ payload: e, ctx: i, mode: c = "interactive", streamTransport: d = null }) => {
1016
+ let p = jt(e);
1017
+ if (!p) return r(i, "bad_request:api", "Parameter id is required.");
1018
+ let g = e, _ = Mt(g), v = vt(process.env.PLAYWRIGHT), x = !vt(process.env.AGENT_SDK_LIVE_CHAT) && v || process.env.NODE_ENV === "test";
1019
+ if (!_) return r(i, "bad_request:api", "Parameter selectedChatModel is required.");
1020
+ if (_ === ft && (x = !0), _ !== ft && (!yt().has(_) || !me(_))) return r(i, "bad_request:api", `Unsupported selectedChatModel: "${_}".`);
1021
+ let S = process.env.OPENAI_API_KEY, C = process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY, w = process.env.XAI_API_KEY, T = ue(_), E = de(_), D = fe(_), O = Nt(g), k = O && O !== "default" && O !== "off" ? O : null, ae = n(_);
1022
+ if (k && !ae.some((e) => e === k)) return r(i, "bad_request:api", `Unsupported reasoning effort "${k}" for selectedChatModel: "${_}".`);
1023
+ if (!x && T && !S) return r(i, "bad_request:provider", "Missing OPENAI_API_KEY.");
1024
+ if (!x && E && !C) return r(i, "bad_request:provider", "Missing GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY).");
1025
+ if (!x && D && !w) return r(i, "bad_request:provider", "Missing XAI_API_KEY.");
1026
+ if (!x && !T && !E && !D) return r(i, "bad_request:provider", `Unsupported selectedChatModel: "${_}".`);
1027
+ let j = await en({
1028
+ ctx: i,
1029
+ chatId: p,
1030
+ selectedChatModel: _
1031
+ }), oe = await a().resolveKnowledge?.({
1032
+ ctx: i,
1033
+ chatId: p,
1034
+ agent: j,
1035
+ selectedChatModel: _
1036
+ }) ?? null, M = await Zt({
1037
+ ctx: i,
1038
+ chatId: p,
1039
+ agent: j,
1040
+ selectedChatModel: _,
1041
+ mode: c
1042
+ }), N = await Qt({
1043
+ ctx: i,
1044
+ chatId: p,
1045
+ agent: j,
1046
+ selectedChatModel: _,
1047
+ mode: c
1048
+ }), se = o(i), P = await l(i, p, { includeDeleted: !0 });
1049
+ if (P?.deletedAt) return r(i, "not_found:chat");
1050
+ P ? P.selectedChatModel !== _ && await u(i, {
1051
+ chatId: p,
1052
+ selectedChatModel: _
1053
+ }) : await h(i, {
1054
+ id: p,
912
1055
  createdAt: /* @__PURE__ */ new Date(),
913
- userId: le.userId,
1056
+ userId: se.userId,
914
1057
  title: "",
915
1058
  isStreaming: !1,
916
- selectedChatModel: h,
1059
+ selectedChatModel: _,
917
1060
  lastContext: null
918
1061
  });
919
- let j = p.message, M = typeof j?.id == "string" ? j.id : D(), N = Array.isArray(j?.parts) ? j?.parts : [];
920
- if ((typeof j?.role == "string" ? j.role : null) === "user") {
1062
+ let F = g.message, ce = typeof F?.id == "string" ? F.id : A(), le = Array.isArray(F?.parts) ? F?.parts : [];
1063
+ if ((typeof F?.role == "string" ? F.role : null) === "user") {
921
1064
  let e = /* @__PURE__ */ new Date();
922
- await u(n, [{
923
- id: M,
924
- chatId: f,
1065
+ await f(i, [{
1066
+ id: ce,
1067
+ chatId: p,
925
1068
  role: "user",
926
- parts: N,
1069
+ parts: le,
927
1070
  attachments: [],
928
1071
  createdAt: e
929
- }]), It({
930
- ctx: n,
931
- chatId: f,
932
- streamTransport: l,
1072
+ }]), nn({
1073
+ ctx: i,
1074
+ chatId: p,
1075
+ streamTransport: d,
933
1076
  message: {
934
- id: M,
1077
+ id: ce,
935
1078
  role: "user",
936
- parts: N,
1079
+ parts: le,
937
1080
  metadata: { createdAt: e.toISOString() }
938
1081
  }
939
1082
  });
940
1083
  }
941
- if (y) {
942
- await c(n, {
943
- chatId: f,
1084
+ if (x) {
1085
+ await y(i, {
1086
+ chatId: p,
944
1087
  isStreaming: !0
945
1088
  });
946
- let e = Ft({
947
- ctx: n,
948
- chatId: f,
949
- mode: o,
950
- streamTransport: l
1089
+ let e = tn({
1090
+ ctx: i,
1091
+ chatId: p,
1092
+ mode: c,
1093
+ streamTransport: d
951
1094
  });
952
1095
  try {
953
- let t = Y(await _t(p, n, f)), r = await s(n, f);
954
- r && qe(r.title) && t && t !== r.title && (await _(n, {
955
- chatId: f,
956
- title: t
957
- }), e.publishJson({
958
- type: "data-chat-title",
959
- data: t,
960
- transient: !0
961
- }));
962
- let i = D();
963
- v && !e.abortController.signal.aborted && await it(600), e.publishJson({
1096
+ if (N) {
1097
+ let t = st(await kt(g, i, p)), n = await l(i, p);
1098
+ n && rt(n.title) && t && t !== n.title && (await s(i, {
1099
+ chatId: p,
1100
+ title: t
1101
+ }), e.publishJson({
1102
+ type: "data-chat-title",
1103
+ data: t,
1104
+ transient: !0
1105
+ }));
1106
+ }
1107
+ let t = A();
1108
+ v && !e.abortController.signal.aborted && await gt(600), e.publishJson({
964
1109
  type: "start",
965
- messageId: i
1110
+ messageId: t
966
1111
  });
967
- let a = "text-1";
1112
+ let n = "text-1";
968
1113
  e.publishJson({
969
1114
  type: "text-start",
970
- id: a
1115
+ id: n
971
1116
  });
972
- let c = vt(p), l = c ? `Echo: ${c}` : "Hello from agents-sdk", d = Date.now(), m = l.split(/(\s+)/).filter((e) => e.length > 0);
973
- for (let t of m) {
1117
+ let r = At(g), a = r ? `Echo: ${r}` : "Hello from agents-sdk", o = Date.now(), u = a.split(/(\s+)/).filter((e) => e.length > 0);
1118
+ for (let t of u) {
974
1119
  if (e.abortController.signal.aborted) break;
975
1120
  e.publishJson({
976
1121
  type: "text-delta",
977
- id: a,
1122
+ id: n,
978
1123
  delta: t
979
- }), await it(v ? 120 : 80);
1124
+ }), await gt(v ? 120 : 80);
980
1125
  }
981
1126
  if (v && !e.abortController.signal.aborted) {
982
- let e = Date.now() - d, t = 1200;
983
- e < t && await it(t - e);
1127
+ let e = Date.now() - o, t = 1200;
1128
+ e < t && await gt(t - e);
984
1129
  }
985
1130
  return e.abortController.signal.aborted ? {} : (e.publishJson({
986
1131
  type: "text-end",
987
- id: a
1132
+ id: n
988
1133
  }), e.publishJson({
989
1134
  type: "finish",
990
1135
  finishReason: "stop"
991
- }), e.publishDone(), await u(n, [{
992
- id: i,
993
- chatId: f,
1136
+ }), e.publishDone(), await f(i, [{
1137
+ id: t,
1138
+ chatId: p,
994
1139
  role: "assistant",
995
1140
  parts: [{
996
1141
  type: "text",
997
- text: l
1142
+ text: a
998
1143
  }],
999
1144
  attachments: [],
1000
1145
  createdAt: /* @__PURE__ */ new Date()
1001
- }]), await Q({
1002
- ctx: n,
1003
- usageContext: k,
1004
- agent: O,
1005
- chatId: f,
1006
- mode: o,
1146
+ }]), await $({
1147
+ ctx: i,
1148
+ usageContext: M,
1149
+ agent: j,
1150
+ chatId: p,
1151
+ mode: c,
1007
1152
  feature: "chat",
1008
- modelId: h,
1153
+ modelId: _,
1009
1154
  status: "success",
1010
1155
  billable: !1,
1011
- usage: jt(),
1156
+ usage: Xt(),
1012
1157
  finishReason: "stop",
1013
- startedAt: new Date(d)
1158
+ startedAt: new Date(o)
1014
1159
  }), {});
1015
1160
  } finally {
1016
- await at(n, f);
1161
+ await _t(i, p);
1017
1162
  }
1018
1163
  }
1019
- let P = Dt(n), F = Ct(p);
1020
- if (Array.isArray(p.messages) && !F) {
1021
- let e = p.messages.flatMap((e) => {
1164
+ let I = zt(i), L = Ft(g);
1165
+ if (Array.isArray(g.messages) && !L) {
1166
+ let e = g.messages.flatMap((e) => {
1022
1167
  let t = typeof e?.id == "string" ? e.id : null, n = typeof e?.role == "string" ? e.role : null, r = Array.isArray(e?.parts) ? e.parts : [];
1023
1168
  return !t || !n ? [] : [{
1024
1169
  id: t,
1025
- chatId: f,
1170
+ chatId: p,
1026
1171
  role: n,
1027
1172
  parts: r,
1028
1173
  attachments: [],
1029
- createdAt: Et(e?.metadata) ?? /* @__PURE__ */ new Date()
1174
+ createdAt: Rt(e?.metadata) ?? /* @__PURE__ */ new Date()
1030
1175
  }];
1031
1176
  });
1032
- e.length > 0 && await u(n, e);
1177
+ e.length > 0 && await f(i, e);
1033
1178
  }
1034
- let I;
1035
- if (Array.isArray(p.messages) && p.messages.length > 0 && F) {
1036
- let e = await d(n, f);
1037
- if (e.length === 0) I = p.messages;
1179
+ let R;
1180
+ if (Array.isArray(g.messages) && g.messages.length > 0 && L) {
1181
+ let e = await m(i, p);
1182
+ if (e.length === 0) R = g.messages;
1038
1183
  else {
1039
- let { changedMessages: t, updatedMessages: r } = Tt(e, wt(p.messages));
1040
- t.length > 0 && await u(n, t), I = r.map((e) => ({
1184
+ let { changedMessages: t, updatedMessages: n } = Lt(e, It(g.messages));
1185
+ t.length > 0 && await f(i, t), R = n.map((e) => ({
1041
1186
  id: e.id,
1042
1187
  role: e.role,
1043
1188
  parts: e.parts,
1044
1189
  metadata: { createdAt: e.createdAt.toISOString() }
1045
1190
  }));
1046
1191
  }
1047
- } else I = Array.isArray(p.messages) && p.messages.length > 0 ? p.messages : (await d(n, f)).map((e) => ({
1192
+ } else R = Array.isArray(g.messages) && g.messages.length > 0 ? g.messages : (await m(i, p)).map((e) => ({
1048
1193
  id: e.id,
1049
1194
  role: e.role,
1050
1195
  parts: e.parts,
1051
1196
  metadata: { createdAt: e.createdAt.toISOString() }
1052
1197
  }));
1053
- let L = F ? {
1054
- messages: I,
1055
- lastContext: A?.lastContext ?? null,
1198
+ let z = L ? {
1199
+ messages: R,
1200
+ lastContext: P?.lastContext ?? null,
1056
1201
  lastContextChanged: !1
1057
- } : await Be({
1058
- ctx: n,
1059
- chatId: f,
1060
- agent: O,
1061
- selectedChatModel: h,
1062
- mode: o,
1063
- messages: I,
1064
- lastContext: A?.lastContext ?? null
1202
+ } : await He({
1203
+ ctx: i,
1204
+ chatId: p,
1205
+ agent: j,
1206
+ selectedChatModel: _,
1207
+ mode: c,
1208
+ messages: R,
1209
+ lastContext: P?.lastContext ?? null
1065
1210
  });
1066
- if (!F && L.lastContextChanged) try {
1067
- await g(n, {
1068
- chatId: f,
1069
- lastContext: L.lastContext
1211
+ if (!L && z.lastContextChanged) try {
1212
+ await b(i, {
1213
+ chatId: p,
1214
+ lastContext: z.lastContext
1070
1215
  });
1071
1216
  } catch (e) {
1072
1217
  console.warn("Failed to save compacted agent chat history context.", e);
1073
1218
  }
1074
- let R = L.messages;
1075
- await c(n, {
1076
- chatId: f,
1219
+ let B = z.messages;
1220
+ await y(i, {
1221
+ chatId: p,
1077
1222
  isStreaming: !0
1078
1223
  });
1079
- let z = Ft({
1080
- ctx: n,
1081
- chatId: f,
1082
- mode: o,
1083
- streamTransport: l
1084
- }), B = "", V = "";
1085
- try {
1086
- B = await _t(p, n, f), V = Y(B);
1087
- let e = await s(n, f);
1088
- e && qe(e.title) && V && V !== e.title && (await _(n, {
1089
- chatId: f,
1090
- title: V
1091
- }), z.publishJson({
1224
+ let V = tn({
1225
+ ctx: i,
1226
+ chatId: p,
1227
+ mode: c,
1228
+ streamTransport: d
1229
+ }), H = "", U = "";
1230
+ if (N) try {
1231
+ H = await kt(g, i, p), U = st(H);
1232
+ let e = await l(i, p);
1233
+ e && rt(e.title) && U && U !== e.title && (await s(i, {
1234
+ chatId: p,
1235
+ title: U
1236
+ }), V.publishJson({
1092
1237
  type: "data-chat-title",
1093
- data: V,
1238
+ data: U,
1094
1239
  transient: !0
1095
1240
  }));
1096
1241
  } catch (e) {
1097
- console.error(e), z.publishJson({
1242
+ Q("Failed to prepare agent chat title.", e, {
1243
+ chatId: p,
1244
+ selectedChatModel: _,
1245
+ agentId: j.id,
1246
+ mode: c
1247
+ }), V.publishJson({
1098
1248
  type: "error",
1099
1249
  errorText: "Something went wrong."
1100
- }), z.publishDone();
1250
+ }), V.publishDone();
1101
1251
  try {
1102
- await at(n, f);
1252
+ await _t(i, p);
1103
1253
  } catch (e) {
1104
- console.error("Failed to update chat streaming state.", e);
1254
+ Q("Failed to update chat streaming state.", e, {
1255
+ chatId: p,
1256
+ selectedChatModel: _,
1257
+ agentId: j.id,
1258
+ mode: c
1259
+ });
1105
1260
  }
1106
1261
  return {};
1107
1262
  }
1108
- B && V && b && (async () => {
1263
+ N && H && U && S && (async () => {
1109
1264
  let e = /* @__PURE__ */ new Date();
1110
1265
  try {
1111
- let { text: t } = await ie({
1266
+ let { text: t } = await ne({
1112
1267
  model: ge(),
1113
1268
  system: xe,
1114
- prompt: B,
1269
+ prompt: H,
1115
1270
  onFinish: async (t) => {
1116
- await Q({
1117
- ctx: n,
1118
- usageContext: k,
1119
- agent: O,
1120
- chatId: f,
1121
- mode: o,
1271
+ await $({
1272
+ ctx: i,
1273
+ usageContext: M,
1274
+ agent: j,
1275
+ chatId: p,
1276
+ mode: c,
1122
1277
  feature: "title",
1123
- modelId: rt,
1278
+ modelId: pt,
1124
1279
  status: "success",
1125
1280
  billable: !0,
1126
1281
  usage: t.totalUsage ?? t.usage,
@@ -1128,27 +1283,27 @@ var Qe = /* @__PURE__ */ e({
1128
1283
  startedAt: e
1129
1284
  });
1130
1285
  }
1131
- }), r = Ye(t);
1286
+ }), n = at(t);
1287
+ if (!n) return;
1288
+ let r = await l(i, p);
1132
1289
  if (!r) return;
1133
- let i = await s(n, f);
1134
- if (!i) return;
1135
- i.title !== r && (await _(n, {
1136
- chatId: f,
1137
- title: r
1138
- }), z.publishJson({
1290
+ r.title !== n && (await s(i, {
1291
+ chatId: p,
1292
+ title: n
1293
+ }), V.publishJson({
1139
1294
  type: "data-chat-title",
1140
- data: r,
1295
+ data: n,
1141
1296
  transient: !0
1142
1297
  }));
1143
1298
  } catch (t) {
1144
- await Q({
1145
- ctx: n,
1146
- usageContext: k,
1147
- agent: O,
1148
- chatId: f,
1149
- mode: o,
1299
+ await $({
1300
+ ctx: i,
1301
+ usageContext: M,
1302
+ agent: j,
1303
+ chatId: p,
1304
+ mode: c,
1150
1305
  feature: "title",
1151
- modelId: rt,
1306
+ modelId: pt,
1152
1307
  status: "error",
1153
1308
  billable: !1,
1154
1309
  error: t,
@@ -1156,14 +1311,19 @@ var Qe = /* @__PURE__ */ e({
1156
1311
  }), console.warn("Failed to generate chat title.", t);
1157
1312
  }
1158
1313
  })();
1159
- let ve = ne({
1160
- originalMessages: I,
1161
- onError: (e) => (console.error(e), "Something went wrong."),
1314
+ let ve = te({
1315
+ originalMessages: R,
1316
+ onError: (e) => (Q("Agent chat stream failed.", e, {
1317
+ chatId: p,
1318
+ selectedChatModel: _,
1319
+ agentId: j.id,
1320
+ mode: c
1321
+ }), Kt(e, _)),
1162
1322
  onFinish: async ({ responseMessage: e }) => {
1163
1323
  let t = Array.isArray(e.parts) ? e.parts : [];
1164
- await u(n, [{
1165
- id: e.id ?? D(),
1166
- chatId: f,
1324
+ await f(i, [{
1325
+ id: e.id ?? A(),
1326
+ chatId: p,
1167
1327
  role: e.role ?? "assistant",
1168
1328
  parts: t,
1169
1329
  attachments: [],
@@ -1171,34 +1331,38 @@ var Qe = /* @__PURE__ */ e({
1171
1331
  }]);
1172
1332
  },
1173
1333
  execute: async ({ writer: e }) => {
1174
- let t = Ke({
1175
- ctx: n,
1334
+ let t = Xe({
1335
+ ctx: i,
1176
1336
  dataStream: e,
1177
- requestHints: P
1178
- }), i = [
1337
+ requestHints: I
1338
+ }), n = [
1179
1339
  "getWeather",
1180
1340
  "createDocument",
1181
1341
  "editDocument",
1182
1342
  "updateDocument",
1183
1343
  "requestSuggestions",
1184
1344
  "webSearch"
1185
- ], a = [
1345
+ ], r = [
1186
1346
  "getWeather",
1187
1347
  "createDocument",
1188
1348
  "editDocument",
1189
1349
  "updateDocument",
1190
1350
  "requestSuggestions"
1191
- ], s = pe(h), c = s ? [] : x ? i : a, l = t, u = c, d = await r().resolveTools?.({
1192
- ctx: n,
1351
+ ], o = pe(_), s = o ? [] : T ? n : r, l = t, u = s, d = await a().resolveTools?.({
1352
+ ctx: i,
1193
1353
  dataStream: e,
1194
- requestHints: P,
1195
- agent: O,
1196
- selectedChatModel: h,
1354
+ requestHints: I,
1355
+ agent: j,
1356
+ selectedChatModel: _,
1197
1357
  availableTools: t,
1198
- defaultActiveTools: c
1358
+ defaultActiveTools: s
1199
1359
  });
1200
- d && (l = d.tools, u = d.activeTools ?? Object.keys(d.tools));
1201
- let m = await te(R.map((e) => ({
1360
+ d && (l = d.tools, u = d.activeTools ?? Object.keys(d.tools)), u = nt({
1361
+ activeTools: u,
1362
+ availableTools: l,
1363
+ userText: At(g)
1364
+ });
1365
+ let f = await ee(B.map((e) => ({
1202
1366
  role: e?.role,
1203
1367
  parts: e?.parts,
1204
1368
  metadata: e?.metadata
@@ -1206,105 +1370,193 @@ var Qe = /* @__PURE__ */ e({
1206
1370
  tools: l,
1207
1371
  ignoreIncompleteToolCalls: !0
1208
1372
  });
1209
- await ht(n, m), x && gt(m);
1210
- let g = typeof p.openaiReasoningSummary == "string" ? p.openaiReasoningSummary : null, _;
1211
- x && E ? _ = { openai: {
1212
- reasoningEffort: E,
1213
- reasoningSummary: g ?? void 0
1214
- } } : w && s && E && (_ = { xai: { reasoningEffort: E } });
1215
- let ee = !1, v = /* @__PURE__ */ new Date(), y = async ({ status: e, usage: t, finishReason: r, error: i }) => {
1216
- ee || (ee = !0, await Q({
1217
- ctx: n,
1218
- usageContext: k,
1219
- agent: O,
1220
- chatId: f,
1221
- mode: o,
1373
+ await Dt(i, f), T && Ot(f);
1374
+ let m = typeof g.openaiReasoningSummary == "string" ? g.openaiReasoningSummary : null, h;
1375
+ T && k ? h = { openai: {
1376
+ reasoningEffort: k,
1377
+ reasoningSummary: m ?? void 0
1378
+ } } : D && o && k && (h = { xai: { reasoningEffort: k } });
1379
+ let v = !1, y = /* @__PURE__ */ new Date(), b = async ({ status: e, usage: t, finishReason: n, error: r }) => {
1380
+ v || (v = !0, await $({
1381
+ ctx: i,
1382
+ usageContext: M,
1383
+ agent: j,
1384
+ chatId: p,
1385
+ mode: c,
1222
1386
  feature: "chat",
1223
- modelId: h,
1387
+ modelId: _,
1224
1388
  status: e,
1225
1389
  billable: e === "success",
1226
1390
  usage: t,
1227
- finishReason: r,
1228
- error: i,
1229
- startedAt: v
1391
+ finishReason: n,
1392
+ error: r,
1393
+ startedAt: y
1230
1394
  }));
1231
- }, b = S({
1232
- model: he(h),
1233
- system: _e({
1234
- selectedChatModel: h,
1235
- requestHints: P,
1236
- agentInstructions: O.instructions,
1237
- knowledge: ce
1238
- }),
1239
- messages: m,
1240
- tools: l,
1241
- stopWhen: oe(5),
1242
- abortSignal: z.abortController.signal,
1243
- providerOptions: _,
1244
- activeTools: u,
1245
- onFinish: async (e) => {
1246
- await y({
1247
- status: "success",
1248
- usage: e.totalUsage ?? e.usage,
1249
- finishReason: e.finishReason
1250
- });
1251
- },
1252
- onError: async (e) => {
1253
- await y({
1254
- status: "error",
1255
- error: e?.error ?? e
1256
- });
1257
- },
1258
- onAbort: async (e) => {
1259
- await y({
1260
- status: "aborted",
1261
- usage: e?.totalUsage ?? e?.usage,
1262
- finishReason: e?.finishReason
1395
+ }, x = Ut(_), S = !1, C, te = () => {
1396
+ C &&= (clearTimeout(C), void 0);
1397
+ }, w = (t, n) => {
1398
+ S && t !== "thinking" || e.write({
1399
+ type: "data-waiting-status",
1400
+ data: {
1401
+ phase: t,
1402
+ message: n,
1403
+ modelId: _,
1404
+ modelName: x
1405
+ },
1406
+ transient: !0
1407
+ });
1408
+ }, ne = () => {
1409
+ S || (S = !0, te(), w("thinking", "Thinking..."));
1410
+ }, E = () => {
1411
+ S = !0, te();
1412
+ };
1413
+ w("waiting", "Waiting..."), C = setTimeout(() => {
1414
+ w("still-waiting", "Still waiting...");
1415
+ }, mt);
1416
+ let O = (() => {
1417
+ try {
1418
+ return ie({
1419
+ model: he(_),
1420
+ system: _e({
1421
+ selectedChatModel: _,
1422
+ requestHints: I,
1423
+ agentInstructions: j.instructions,
1424
+ knowledge: oe
1425
+ }),
1426
+ messages: f,
1427
+ tools: l,
1428
+ stopWhen: re(5),
1429
+ abortSignal: V.abortController.signal,
1430
+ providerOptions: h,
1431
+ activeTools: u,
1432
+ onFinish: async (e) => {
1433
+ E(), await b({
1434
+ status: "success",
1435
+ usage: e.totalUsage ?? e.usage,
1436
+ finishReason: e.finishReason
1437
+ });
1438
+ },
1439
+ onError: async (e) => {
1440
+ E();
1441
+ let t = e?.error ?? e;
1442
+ Q("Agent model stream failed.", t, {
1443
+ chatId: p,
1444
+ selectedChatModel: _,
1445
+ agentId: j.id,
1446
+ mode: c
1447
+ }), await b({
1448
+ status: "error",
1449
+ error: t
1450
+ });
1451
+ },
1452
+ onAbort: async (e) => {
1453
+ E(), await b({
1454
+ status: "aborted",
1455
+ usage: e?.totalUsage ?? e?.usage,
1456
+ finishReason: e?.finishReason
1457
+ });
1458
+ },
1459
+ onChunk: ({ chunk: e }) => {
1460
+ Wt(e) && ne();
1461
+ }
1263
1462
  });
1463
+ } catch (e) {
1464
+ throw E(), e;
1264
1465
  }
1265
- });
1266
- e.merge(b.toUIMessageStream({
1267
- originalMessages: I,
1268
- sendReasoning: s || !!(x && E)
1466
+ })();
1467
+ e.merge(O.toUIMessageStream({
1468
+ originalMessages: R,
1469
+ onError: (e) => Kt(e, _),
1470
+ sendReasoning: o || !!(T && k)
1269
1471
  }));
1270
1472
  }
1271
1473
  });
1272
1474
  return (async () => {
1273
- let e = null;
1475
+ let e = null, n = null, r = Date.now(), a = !1, o = null, s = async () => {
1476
+ let e = Date.now();
1477
+ if (!(e - r < 6e4)) {
1478
+ r = e;
1479
+ try {
1480
+ await y(i, {
1481
+ chatId: p,
1482
+ isStreaming: !0
1483
+ });
1484
+ } catch (e) {
1485
+ console.warn("Failed to refresh chat streaming heartbeat.", e);
1486
+ }
1487
+ }
1488
+ }, l = () => {
1489
+ if (!a || o) return;
1490
+ let e = s().finally(() => {
1491
+ o === e && (o = null);
1492
+ });
1493
+ o = e;
1494
+ }, u = () => {
1495
+ a = !0;
1496
+ let e = setInterval(() => {
1497
+ l();
1498
+ }, t);
1499
+ return async () => {
1500
+ a = !1, clearInterval(e), await o;
1501
+ };
1502
+ };
1274
1503
  try {
1275
1504
  let t = ve.getReader();
1276
- for (e = () => t.releaseLock();;) {
1505
+ for (e = () => t.releaseLock(), n = u();;) {
1277
1506
  let { value: e, done: n } = await t.read();
1278
1507
  if (n) break;
1279
- z.publishJson(e);
1508
+ V.publishJson(e), await s();
1280
1509
  }
1281
- z.publishDone();
1510
+ V.publishDone();
1282
1511
  } catch (e) {
1283
- console.error(e), z.publishJson({
1512
+ Q("Agent chat runtime stream failed.", e, {
1513
+ chatId: p,
1514
+ selectedChatModel: _,
1515
+ agentId: j.id,
1516
+ mode: c
1517
+ }), V.publishJson({
1284
1518
  type: "error",
1285
- errorText: "Something went wrong."
1286
- }), z.publishDone();
1519
+ errorText: Kt(e, _)
1520
+ }), V.publishDone();
1287
1521
  } finally {
1288
- e?.();
1522
+ await n?.(), e?.();
1289
1523
  try {
1290
- await at(n, f);
1524
+ await _t(i, p);
1291
1525
  } catch (e) {
1292
- console.error("Failed to update chat streaming state.", e);
1526
+ Q("Failed to update chat streaming state.", e, {
1527
+ chatId: p,
1528
+ selectedChatModel: _,
1529
+ agentId: j.id,
1530
+ mode: c
1531
+ });
1293
1532
  }
1294
1533
  }
1295
1534
  })(), {};
1296
- }, Lt = async (e, t) => $({
1297
- payload: e,
1298
- ctx: t,
1299
- mode: "interactive"
1300
- }), Rt = async (e, t) => {
1301
- let n = t.req.query.id, r = Array.isArray(n) ? n[0] : n;
1302
- return typeof r != "string" || r.trim() === "" ? a(t, "bad_request:api") : p(t, r);
1303
- }, zt = (e) => {
1304
- e.get(Ze, (async (e, t) => {
1305
- let n = t.req.query.id, r = Array.isArray(n) ? n[0] : n;
1306
- return typeof r != "string" || r.trim() === "" ? a(t, "bad_request:api", "Parameter id is required.") : await s(t, r) || a(t, "not_found:chat");
1307
- })), e.post(Ze, Lt), e.delete(Ze, Rt);
1535
+ }, an = async (e, t) => {
1536
+ try {
1537
+ return await rn({
1538
+ payload: e,
1539
+ ctx: t,
1540
+ mode: "interactive"
1541
+ });
1542
+ } catch (n) {
1543
+ return Q("Agent chat request failed.", n, {
1544
+ ...Jt(e),
1545
+ mode: "interactive"
1546
+ }), r(t, "internal:api");
1547
+ }
1548
+ }, on = async (e, t) => {
1549
+ let n = t.req.query.id, i = Array.isArray(n) ? n[0] : n;
1550
+ return typeof i != "string" || i.trim() === "" ? r(t, "bad_request:api") : g(t, i);
1551
+ }, sn = (t) => {
1552
+ t.get(ct, (async (t, n) => {
1553
+ let i = n.req.query.id, a = Array.isArray(i) ? i[0] : i;
1554
+ if (typeof a != "string" || a.trim() === "") return r(n, "bad_request:api", "Parameter id is required.");
1555
+ let o = await l(n, a);
1556
+ if (!o) return r(n, "not_found:chat");
1557
+ let s = x(a);
1558
+ return e(o) && (!s || s.isDone) && (o = await d(n, o)), o;
1559
+ })), t.post(ct, an), t.delete(ct, on);
1308
1560
  };
1309
1561
  //#endregion
1310
- export { $ as n, Qe as t };
1562
+ export { sn as default, rn as runAgentLoop };