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