@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,41 +1,41 @@
1
- import { r as e, t } from "./chat-streaming-CaGHOBwC.js";
1
+ import { c as e, o as t } from "./message-visibility-zTseZa3P.js";
2
2
  import { i as n } from "./openai-reasoning-BCA05blq.js";
3
3
  import { t as r } from "./apiErrors-DKcH9vz9.js";
4
4
  import { i, r as a, t as o } from "./chatCtx-C8Ba-LB7.js";
5
- import { S as s, _ as c, a as l, b as u, f as d, g as f, h as p, l as m, m as h, n as g, s as _, v, x as y, y as b } from "./chatDb-MmVCT1uj.js";
6
- import { n as x, t as ee } from "./resumableSse-CmmkOGyv.js";
7
- import { Output as te, convertToModelMessages as ne, createUIMessageStream as re, extractReasoningMiddleware as ie, generateText as ae, smoothStream as S, stepCountIs as oe, streamObject as C, streamText as se, tool as w, wrapLanguageModel as T } from "ai";
8
- import { getTenantFilesystemDb as E } from "@rpcbase/db";
9
- import { createHash as ce, randomUUID as D } from "node:crypto";
10
- import { GridFSBucket as O, ObjectId as le } from "mongodb";
11
- import { createGoogleGenerativeAI as k } from "@ai-sdk/google";
12
- import { openai as A } from "@ai-sdk/openai";
13
- import { createXai as ue } from "@ai-sdk/xai";
14
- import { z as j } from "zod";
5
+ import { S as s, _ as c, a as l, b as u, f as d, g as f, h as p, l as m, m as h, n as g, s as _, v, x as y, y as b } from "./chatDb-DLQOzat8.js";
6
+ import { n as x, t as S } from "./resumableSse-CmmkOGyv.js";
7
+ import { Output as C, convertToModelMessages as ee, createUIMessageStream as te, extractReasoningMiddleware as w, generateText as ne, smoothStream as T, stepCountIs as re, streamObject as E, streamText as ie, tool as D, wrapLanguageModel as O } from "ai";
8
+ import { getTenantFilesystemDb as k } from "@rpcbase/db";
9
+ import { createHash as ae, randomUUID as A } from "node:crypto";
10
+ import { GridFSBucket as j, ObjectId as oe } from "mongodb";
11
+ import { createGoogleGenerativeAI as M } from "@ai-sdk/google";
12
+ import { openai as N } from "@ai-sdk/openai";
13
+ import { createXai as se } from "@ai-sdk/xai";
14
+ import { z as P } from "zod";
15
15
  //#region src/api/chat/models.ts
16
- var M = /-thinking$/, N = "openai/", P = "google/", F = "xai/", I = new Set([
16
+ var F = /-thinking$/, ce = "openai/", le = "google/", I = "xai/", L = new Set([
17
17
  "openai/gpt-5.4-mini",
18
18
  "openai/gpt-5.5",
19
19
  "google/gemini-3.5-flash",
20
20
  "xai/grok-4.3-thinking"
21
- ]), de = (e) => e.startsWith(N), fe = (e) => e.startsWith(P), L = (e) => e.startsWith(F), pe = (e) => e.endsWith("-thinking"), me = (e) => e.includes("/") ? de(e) || fe(e) || L(e) : !1, R = ue({
21
+ ]), ue = (e) => e.startsWith(ce), de = (e) => e.startsWith(le), fe = (e) => e.startsWith(I), pe = (e) => e.endsWith("-thinking"), me = (e) => e.includes("/") ? ue(e) || de(e) || fe(e) : !1, R = se({
22
22
  baseURL: process.env.XAI_BASE_URL ?? "https://api.x.ai/v1",
23
23
  apiKey: process.env.XAI_API_KEY
24
- }), z = k({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY }), he = (e) => {
25
- if (de(e)) return A.responses(e.slice(N.length));
26
- if (fe(e)) {
27
- let t = e.slice(P.length).replace(M, ""), n = z.chat(t);
28
- return pe(e) ? T({
24
+ }), z = M({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY }), he = (e) => {
25
+ if (ue(e)) return N.responses(e.slice(ce.length));
26
+ if (de(e)) {
27
+ let t = e.slice(le.length).replace(F, ""), n = z.chat(t);
28
+ return pe(e) ? O({
29
29
  model: n,
30
- middleware: ie({ tagName: "thinking" })
30
+ middleware: w({ tagName: "thinking" })
31
31
  }) : n;
32
32
  }
33
- if (L(e)) {
34
- let t = e.slice(F.length).replace(M, "");
33
+ if (fe(e)) {
34
+ let t = e.slice(I.length).replace(F, "");
35
35
  return pe(e) ? R.responses(t) : R.chat(t);
36
36
  }
37
37
  throw Error(`Unsupported modelId: ${e}`);
38
- }, ge = () => A.chat("gpt-5.4-mini"), B = () => A.chat(process.env.AGENT_SDK_ARTIFACT_MODEL ?? "gpt-5.4-mini"), V = "\nArtifacts is a special user interface mode that helps users with writing, editing, and other content creation tasks. When artifact is open, it is on the right side of the screen, while the conversation is on the left side. When creating, editing, or updating documents, changes are reflected in real-time on the artifacts and visible to the user.\n\nWhen asked to write code, always use artifacts. When writing code, specify the language in the backticks, e.g. ```python`code here```. The default language is Python. Other languages are not yet supported, so let the user know if they request a different language.\n\nCritical rules:\n- Only call one artifact tool per response.\n- Do not update or edit a document immediately after creating it. Wait for user feedback or an explicit request to modify it.\n- After creating, editing, or updating an artifact, do not repeat the full artifact content in chat. The user can already see it.\n\nThis is a guide for using artifacts tools: `createDocument`, `editDocument`, `updateDocument`, and `requestSuggestions`, which render content on artifacts beside the conversation.\n\n**When to use `createDocument`:**\n- For substantial content (>10 lines) or code\n- For content users will likely save/reuse (emails, code, essays, etc.)\n- When explicitly requested to create a document\n- For when content contains a single code snippet\n- Use kind \"code\" for programming, \"text\" for writing, and \"sheet\" for tabular/CSV data\n\n**When NOT to use `createDocument`:**\n- For informational/explanatory content\n- For conversational responses\n- When asked to keep it in chat\n\n**Using `editDocument`:**\n- Prefer this for targeted edits to an existing artifact\n- For scripts: fixing bugs, adding/removing lines, renaming variables, adding logs\n- For documents: fixing typos, rewording paragraphs, inserting or replacing sections\n- Provide an exact `old_string` and `new_string`\n- Include enough surrounding context in `old_string` to make the match unique\n- Use `replace_all: true` only for deliberate repeated replacements, like renaming a variable everywhere\n\n**Using `updateDocument`:**\n- Default to full document rewrites for major changes\n- Use `editDocument` instead for specific, isolated changes\n- Follow user instructions for which parts to modify\n\n**When NOT to use `editDocument` or `updateDocument`:**\n- Immediately after creating a document\n- Without an explicit user request to modify the artifact\n\n**Using `requestSuggestions`:**\n- ONLY use when the user explicitly asks for suggestions on an existing document\n- Requires a valid document ID from a previously created document\n- Never use for general questions or information requests\n", H = "You are a friendly assistant! Keep your responses concise and helpful.\n\nWhen asked to write, create, or help with something, just do it directly. Don't ask clarifying questions unless absolutely necessary - make reasonable assumptions and proceed with the task.", U = (e) => `\
38
+ }, ge = () => N.chat("gpt-5.4-mini"), B = () => N.chat(process.env.AGENT_SDK_ARTIFACT_MODEL ?? "gpt-5.4-mini"), V = "\nArtifacts is a special user interface mode that helps users with writing, editing, and other content creation tasks. When artifact is open, it is on the right side of the screen, while the conversation is on the left side. When creating, editing, or updating documents, changes are reflected in real-time on the artifacts and visible to the user.\n\nWhen asked to write code, always use artifacts. When writing code, specify the language in the backticks, e.g. ```python`code here```. The default language is Python. Other languages are not yet supported, so let the user know if they request a different language.\n\nCritical rules:\n- Only call one artifact tool per response.\n- Do not update or edit a document immediately after creating it. Wait for user feedback or an explicit request to modify it.\n- After creating, editing, or updating an artifact, do not repeat the full artifact content in chat. The user can already see it.\n\nThis is a guide for using artifacts tools: `createDocument`, `editDocument`, `updateDocument`, and `requestSuggestions`, which render content on artifacts beside the conversation.\n\n**When to use `createDocument`:**\n- For substantial content (>10 lines) or code\n- For content users will likely save/reuse (emails, code, essays, etc.)\n- When explicitly requested to create a document\n- For when content contains a single code snippet\n- Use kind \"code\" for programming, \"text\" for writing, and \"sheet\" for tabular/CSV data\n\n**When NOT to use `createDocument`:**\n- For informational/explanatory content\n- For conversational responses\n- When asked to keep it in chat\n\n**Using `editDocument`:**\n- Prefer this for targeted edits to an existing artifact\n- For scripts: fixing bugs, adding/removing lines, renaming variables, adding logs\n- For documents: fixing typos, rewording paragraphs, inserting or replacing sections\n- Provide an exact `old_string` and `new_string`\n- Include enough surrounding context in `old_string` to make the match unique\n- Use `replace_all: true` only for deliberate repeated replacements, like renaming a variable everywhere\n\n**Using `updateDocument`:**\n- Default to full document rewrites for major changes\n- Use `editDocument` instead for specific, isolated changes\n- Follow user instructions for which parts to modify\n\n**When NOT to use `editDocument` or `updateDocument`:**\n- Immediately after creating a document\n- Without an explicit user request to modify the artifact\n\n**Using `requestSuggestions`:**\n- ONLY use when the user explicitly asks for suggestions on an existing document\n- Requires a valid document ID from a previously created document\n- Never use for general questions or information requests\n", H = "You are a friendly assistant! Keep your responses concise and helpful.\n\nWhen asked to write, create, or help with something, just do it directly. Don't ask clarifying questions unless absolutely necessary - make reasonable assumptions and proceed with the task.", U = (e) => `\
39
39
  About the origin of user's request:
40
40
  - lat: ${e.latitude ?? "unknown"}
41
41
  - lon: ${e.longitude ?? "unknown"}
@@ -202,7 +202,9 @@ ${e}`;
202
202
  errorMessage: e.message,
203
203
  errorStack: e.stack,
204
204
  errorCause: e.cause
205
- } : { errorValue: e }, Ke = async ({ system: e, prompt: t, dataStream: n, providerOptions: r }) => {
205
+ } : { errorValue: e }, Y = (e, t) => {
206
+ console.error(`[agents-sdk:getWeather] ${e}`, t);
207
+ }, Ke = async ({ system: e, prompt: t, dataStream: n, providerOptions: r }) => {
206
208
  if (q()) {
207
209
  let e = `Stub document: ${t}`;
208
210
  return n.write({
@@ -211,10 +213,10 @@ ${e}`;
211
213
  transient: !0
212
214
  }), e;
213
215
  }
214
- let i = "", { fullStream: a } = se({
216
+ let i = "", { fullStream: a } = ie({
215
217
  model: B(),
216
218
  system: e,
217
- experimental_transform: S({ chunking: "word" }),
219
+ experimental_transform: T({ chunking: "word" }),
218
220
  prompt: t,
219
221
  providerOptions: r
220
222
  });
@@ -233,11 +235,11 @@ ${e}`;
233
235
  transient: !0
234
236
  }), e;
235
237
  }
236
- let r = "", { fullStream: i } = C({
238
+ let r = "", { fullStream: i } = E({
237
239
  model: B(),
238
240
  system: e,
239
241
  prompt: t,
240
- schema: j.object({ code: j.string() })
242
+ schema: P.object({ code: P.string() })
241
243
  });
242
244
  for await (let e of i) {
243
245
  if (e.type !== "object") continue;
@@ -258,11 +260,11 @@ ${e}`;
258
260
  transient: !0
259
261
  }), e;
260
262
  }
261
- let r = "", { fullStream: i } = C({
263
+ let r = "", { fullStream: i } = E({
262
264
  model: B(),
263
265
  system: e,
264
266
  prompt: t,
265
- schema: j.object({ csv: j.string().describe("CSV data") })
267
+ schema: P.object({ csv: P.string().describe("CSV data") })
266
268
  });
267
269
  for await (let e of i) {
268
270
  if (e.type !== "object") continue;
@@ -282,82 +284,103 @@ ${e}`;
282
284
  let t = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(e)}&count=1&language=en&format=json`;
283
285
  try {
284
286
  let n = await fetch(t);
285
- if (!n.ok) return console.error("Weather geocoding request failed.", {
287
+ if (!n.ok) return Y("Geocoding request failed.", {
286
288
  city: e,
287
289
  status: n.status,
288
290
  statusText: n.statusText
289
291
  }), null;
290
- let r = await n.json().catch((t) => (console.error("Weather geocoding response parse failed.", {
292
+ let r = await n.json().catch((t) => (Y("Geocoding response parse failed.", {
291
293
  city: e,
292
294
  ...J(t)
293
295
  }), null)), i = Ge(r) && Array.isArray(r.results) ? r.results : [];
294
- if (i.length === 0) return null;
296
+ if (i.length === 0) return Y("Geocoding returned no results.", { city: e }), null;
295
297
  let a = i[0];
296
- if (!Ge(a)) return null;
298
+ if (!Ge(a)) return Y("Geocoding returned an invalid result shape.", {
299
+ city: e,
300
+ result: a
301
+ }), null;
297
302
  let o = a.latitude, s = a.longitude;
298
- return typeof o != "number" || typeof s != "number" ? null : {
303
+ return typeof o != "number" || typeof s != "number" ? (Y("Geocoding result did not include numeric coordinates.", {
304
+ city: e,
305
+ latitude: o,
306
+ longitude: s
307
+ }), null) : {
299
308
  latitude: o,
300
309
  longitude: s
301
310
  };
302
311
  } catch (t) {
303
- return console.error("Weather geocoding request threw.", {
312
+ return Y("Geocoding request threw.", {
304
313
  city: e,
305
314
  ...J(t)
306
315
  }), null;
307
316
  }
308
317
  }, Xe = ({ ctx: e, dataStream: t, requestHints: n }) => {
309
- let r = o(e), i = async (t) => {
318
+ let r = o(e), i = (t) => ({
319
+ input: t,
320
+ requestHints: n,
321
+ tenantId: r.tenantId,
322
+ userId: r.userId,
323
+ route: e.req?.path ?? e.req?.originalUrl ?? e.req?.url
324
+ }), a = async (t) => {
310
325
  let n = await _(e, t);
311
326
  return n.length > 0 ? n.at(-1) ?? null : null;
312
- }, a = w({
327
+ }, s = D({
313
328
  description: "Get the current weather at a location. Use this for direct weather or forecast requests. You can provide either coordinates or a city name.",
314
- inputSchema: j.object({
315
- latitude: j.number().optional(),
316
- longitude: j.number().optional(),
317
- city: j.string().describe("City name (e.g., 'San Francisco', 'New York', 'London')").optional()
329
+ inputSchema: P.object({
330
+ latitude: P.number().optional(),
331
+ longitude: P.number().optional(),
332
+ city: P.string().describe("City name (e.g., 'San Francisco', 'New York', 'London')").optional()
318
333
  }),
319
334
  needsApproval: !0,
320
335
  execute: async (e) => {
321
336
  let t, n;
322
337
  if (e.city) {
323
338
  let r = await Ye(e.city);
324
- if (!r) return { error: `Could not find coordinates for "${e.city}". Please check the city name.` };
339
+ if (!r) return Y("Tool returned an error because city geocoding failed.", {
340
+ ...i(e),
341
+ city: e.city
342
+ }), { error: `Could not find coordinates for "${e.city}". Please check the city name.` };
325
343
  t = r.latitude, n = r.longitude;
326
344
  } else if (e.latitude !== void 0 && e.longitude !== void 0) t = e.latitude, n = e.longitude;
327
- else return { error: "Please provide either a city name or both latitude and longitude coordinates." };
345
+ else return Y("Tool returned an error because location input was missing.", { ...i(e) }), { error: "Please provide either a city name or both latitude and longitude coordinates." };
328
346
  try {
329
347
  let r = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${t}&longitude=${n}&current=temperature_2m&hourly=temperature_2m&daily=sunrise,sunset&timezone=auto`);
330
- if (!r.ok) return console.error("Weather forecast request failed.", {
331
- city: e.city,
348
+ if (!r.ok) return Y("Forecast request failed.", {
349
+ ...i(e),
332
350
  latitude: t,
333
351
  longitude: n,
334
352
  status: r.status,
335
353
  statusText: r.statusText
336
354
  }), { error: "Weather lookup failed. Please try again." };
337
- let i = await r.json().catch((r) => (console.error("Weather forecast response parse failed.", {
338
- city: e.city,
355
+ let a = await r.json().catch((r) => (Y("Forecast response parse failed.", {
356
+ ...i(e),
339
357
  latitude: t,
340
358
  longitude: n,
341
359
  ...J(r)
342
360
  }), null));
343
- return Ge(i) ? ("city" in e && (i.cityName = e.city), i) : { error: "Weather lookup failed. Please try again." };
361
+ return Ge(a) ? ("city" in e && (a.cityName = e.city), a) : (Y("Tool returned an error because forecast response was invalid.", {
362
+ ...i(e),
363
+ latitude: t,
364
+ longitude: n,
365
+ weatherData: a
366
+ }), { error: "Weather lookup failed. Please try again." });
344
367
  } catch (r) {
345
- return console.error("Weather forecast request threw.", {
346
- city: e.city,
368
+ return Y("Forecast request threw.", {
369
+ ...i(e),
347
370
  latitude: t,
348
371
  longitude: n,
349
372
  ...J(r)
350
373
  }), { error: "Weather lookup failed. Please try again." };
351
374
  }
352
375
  }
353
- }), s = w({
376
+ }), l = D({
354
377
  description: "Create an artifact for writing or content creation. Use kind 'code' for programming, 'text' for writing, and 'sheet' for spreadsheets or tabular data.",
355
- inputSchema: j.object({
356
- title: j.string().describe("The title of the artifact"),
357
- kind: j.enum(Ue).describe("Use 'code' for programming, 'text' for prose, and 'sheet' for CSV/tabular data")
378
+ inputSchema: P.object({
379
+ title: P.string().describe("The title of the artifact"),
380
+ kind: P.enum(Ue).describe("Use 'code' for programming, 'text' for prose, and 'sheet' for CSV/tabular data")
358
381
  }),
359
382
  execute: async ({ title: n, kind: r }) => {
360
- let i = D();
383
+ let i = A();
361
384
  t.write({
362
385
  type: "data-kind",
363
386
  data: r,
@@ -404,17 +427,17 @@ ${e}`;
404
427
  content: r === "code" ? "A script was created and is now visible to the user." : "A document was created and is now visible to the user."
405
428
  };
406
429
  }
407
- }), l = w({
430
+ }), u = D({
408
431
  description: "Fully rewrite an existing artifact with the given description. Use editDocument instead for targeted find-and-replace changes.",
409
- inputSchema: j.object({
410
- id: j.string().describe("The ID of the artifact to rewrite"),
411
- description: j.string().default("Improve the content").describe("The description of changes that need to be made")
432
+ inputSchema: P.object({
433
+ id: P.string().describe("The ID of the artifact to rewrite"),
434
+ description: P.string().default("Improve the content").describe("The description of changes that need to be made")
412
435
  }),
413
436
  execute: async ({ id: n, description: r }) => {
414
- let a = await i(n);
415
- if (!a) return { error: "Document not found" };
416
- let o = a.kind;
417
- if (!Ue.includes(o)) return { error: `Unsupported document kind: ${a.kind}` };
437
+ let i = await a(n);
438
+ if (!i) return { error: "Document not found" };
439
+ let o = i.kind;
440
+ if (!Ue.includes(o)) return { error: `Unsupported document kind: ${i.kind}` };
418
441
  t.write({
419
442
  type: "data-clear",
420
443
  data: null,
@@ -422,57 +445,57 @@ ${e}`;
422
445
  });
423
446
  let s = "";
424
447
  return o === "text" ? s = await Ke({
425
- system: be(a.content, a.kind),
448
+ system: be(i.content, i.kind),
426
449
  prompt: r,
427
450
  dataStream: t,
428
451
  providerOptions: { openai: { prediction: {
429
452
  type: "content",
430
- content: a.content
453
+ content: i.content
431
454
  } } }
432
455
  }) : o === "code" ? s = await qe({
433
- system: be(a.content, a.kind),
456
+ system: be(i.content, i.kind),
434
457
  prompt: r,
435
458
  dataStream: t
436
459
  }) : o === "sheet" && (s = await Je({
437
- system: be(a.content, a.kind),
460
+ system: be(i.content, i.kind),
438
461
  prompt: r,
439
462
  dataStream: t
440
463
  })), await p(e, {
441
- id: a.id,
442
- title: a.title,
443
- kind: a.kind,
464
+ id: i.id,
465
+ title: i.title,
466
+ kind: i.kind,
444
467
  content: s
445
468
  }), t.write({
446
469
  type: "data-finish",
447
470
  data: null,
448
471
  transient: !0
449
472
  }), {
450
- id: a.id,
451
- title: a.title,
452
- kind: a.kind,
453
- content: a.kind === "code" ? "The script has been updated successfully." : "The document has been updated successfully."
473
+ id: i.id,
474
+ title: i.title,
475
+ kind: i.kind,
476
+ content: i.kind === "code" ? "The script has been updated successfully." : "The document has been updated successfully."
454
477
  };
455
478
  }
456
479
  });
457
480
  return {
458
- getWeather: a,
459
- createDocument: s,
460
- editDocument: w({
481
+ getWeather: s,
482
+ createDocument: l,
483
+ editDocument: D({
461
484
  description: "Make a targeted edit to an existing artifact by replacing an exact string. Prefer this over updateDocument for small changes, fixes, renames, and isolated edits.",
462
- inputSchema: j.object({
463
- id: j.string().describe("The ID of the artifact to edit"),
464
- old_string: j.string().min(1).describe("Exact string to find. Include enough surrounding context to make the match unique."),
465
- new_string: j.string().describe("Replacement string"),
466
- replace_all: j.boolean().optional().describe("Replace all occurrences instead of only the first one")
485
+ inputSchema: P.object({
486
+ id: P.string().describe("The ID of the artifact to edit"),
487
+ old_string: P.string().min(1).describe("Exact string to find. Include enough surrounding context to make the match unique."),
488
+ new_string: P.string().describe("Replacement string"),
489
+ replace_all: P.boolean().optional().describe("Replace all occurrences instead of only the first one")
467
490
  }),
468
- execute: async ({ id: n, old_string: r, new_string: a, replace_all: o }) => {
469
- let s = await i(n);
491
+ execute: async ({ id: n, old_string: r, new_string: i, replace_all: o }) => {
492
+ let s = await a(n);
470
493
  if (!s) return { error: "Document not found" };
471
494
  if (!s.content) return { error: "Document has no content" };
472
495
  let c = s.kind;
473
496
  if (!Ue.includes(c)) return { error: `Unsupported document kind: ${s.kind}` };
474
497
  if (!s.content.includes(r)) return { error: "old_string not found in document" };
475
- let l = o ? s.content.replaceAll(r, a) : s.content.replace(r, a);
498
+ let l = o ? s.content.replaceAll(r, i) : s.content.replace(r, i);
476
499
  return await p(e, {
477
500
  id: s.id,
478
501
  title: s.title,
@@ -506,59 +529,59 @@ ${e}`;
506
529
  };
507
530
  }
508
531
  }),
509
- updateDocument: l,
510
- requestSuggestions: w({
532
+ updateDocument: u,
533
+ requestSuggestions: D({
511
534
  description: "Request writing suggestions for an existing document artifact. Only use this when the user explicitly asks to improve or get suggestions for a document they have already created. Never use for general questions.",
512
- inputSchema: j.object({ documentId: j.string().describe("The UUID of an existing document artifact that was previously created with createDocument") }),
535
+ inputSchema: P.object({ documentId: P.string().describe("The UUID of an existing document artifact that was previously created with createDocument") }),
513
536
  execute: async ({ documentId: n }) => {
514
- let a = await i(n);
515
- if (!a?.content) return { error: "Document not found" };
537
+ let i = await a(n);
538
+ if (!i?.content) return { error: "Document not found" };
516
539
  if (q()) {
517
- let i = {
540
+ let a = {
518
541
  originalText: "Stub original sentence.",
519
542
  suggestedText: "Stub suggested sentence.",
520
543
  description: "Stub suggestion",
521
- id: D(),
544
+ id: A(),
522
545
  documentId: n,
523
- documentCreatedAt: a.createdAt,
546
+ documentCreatedAt: i.createdAt,
524
547
  isResolved: !1,
525
548
  userId: r.userId,
526
549
  createdAt: /* @__PURE__ */ new Date()
527
550
  };
528
551
  return t.write({
529
552
  type: "data-suggestion",
530
- data: i,
553
+ data: a,
531
554
  transient: !0
532
555
  }), await c(e, {
533
556
  documentId: n,
534
- suggestions: [i]
557
+ suggestions: [a]
535
558
  }), {
536
559
  id: n,
537
- title: a.title,
538
- kind: a.kind,
560
+ title: i.title,
561
+ kind: i.kind,
539
562
  message: "Suggestions have been added to the document"
540
563
  };
541
564
  }
542
- let o = [], { partialOutputStream: s } = se({
565
+ let o = [], { partialOutputStream: s } = ie({
543
566
  model: B(),
544
567
  system: "You are a help writing assistant. Given a piece of writing, please offer suggestions to improve the piece of writing and describe the change. It is very important for the edits to contain full sentences instead of just words. Max 5 suggestions.",
545
- prompt: a.content,
546
- output: te.array({ element: j.object({
547
- originalSentence: j.string().describe("The original sentence"),
548
- suggestedSentence: j.string().describe("The suggested sentence"),
549
- description: j.string().describe("The description of the suggestion")
568
+ prompt: i.content,
569
+ output: C.array({ element: P.object({
570
+ originalSentence: P.string().describe("The original sentence"),
571
+ suggestedSentence: P.string().describe("The suggested sentence"),
572
+ description: P.string().describe("The description of the suggestion")
550
573
  }) })
551
574
  }), l = 0;
552
- for await (let e of s) if (e) for (let i = l; i < e.length; i++) {
553
- let s = e[i];
575
+ for await (let e of s) if (e) for (let a = l; a < e.length; a++) {
576
+ let s = e[a];
554
577
  if (!s?.originalSentence || !s?.suggestedSentence || !s?.description) continue;
555
578
  let c = {
556
579
  originalText: s.originalSentence,
557
580
  suggestedText: s.suggestedSentence,
558
581
  description: s.description,
559
- id: D(),
582
+ id: A(),
560
583
  documentId: n,
561
- documentCreatedAt: a.createdAt,
584
+ documentCreatedAt: i.createdAt,
562
585
  isResolved: !1,
563
586
  userId: r.userId,
564
587
  createdAt: /* @__PURE__ */ new Date()
@@ -574,13 +597,13 @@ ${e}`;
574
597
  suggestions: o
575
598
  }), {
576
599
  id: n,
577
- title: a.title,
578
- kind: a.kind,
600
+ title: i.title,
601
+ kind: i.kind,
579
602
  message: "Suggestions have been added to the document"
580
603
  };
581
604
  }
582
605
  }),
583
- webSearch: A.tools.webSearch({
606
+ webSearch: N.tools.webSearch({
584
607
  externalWebAccess: !0,
585
608
  searchContextSize: "medium",
586
609
  userLocation: {
@@ -612,37 +635,43 @@ ${e}`;
612
635
  }, ot = (e) => {
613
636
  let t = e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").replace(/\s+/g, " ").trim();
614
637
  return t === "hi" || t === "hello" || t === "hey" || t === "salut" || t === "bonjour";
615
- }, Y = (e) => {
638
+ }, st = (e) => {
616
639
  let t = e.trim();
617
640
  return !t || ot(t) ? "" : at(t.replaceAll("\n", " ").replaceAll("\r", " ").split(/\s+/).filter((e) => e.trim() !== "").slice(0, 5).join(" "));
618
- }, st = "/api/rb/agents/chat";
619
- j.any(), j.any();
620
- var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt = "test-model", ft = "openai/gpt-5.4-mini", pt = async (e) => new Promise((t) => setTimeout(t, e)), mt = async (e, t) => {
641
+ }, ct = "/api/rb/agents/chat";
642
+ P.any(), P.any();
643
+ var lt = 1024 * 1024 * 20, ut = 1e5, dt = /^\/api\/rb\/files\/([^/]+)\/?$/, ft = "test-model", pt = "openai/gpt-5.4-mini", mt = 9e3, ht = new Set([
644
+ "start",
645
+ "start-step",
646
+ "finish-step",
647
+ "finish",
648
+ "raw"
649
+ ]), gt = async (e) => new Promise((t) => setTimeout(t, e)), _t = async (e, t) => {
621
650
  let n = x(t);
622
651
  n && !n.isDone || await y(e, {
623
652
  chatId: t,
624
653
  isStreaming: !1
625
654
  });
626
- }, ht = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, X = (e) => typeof e == "string" && e.trim() || null, gt = () => {
655
+ }, vt = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, X = (e) => typeof e == "string" && e.trim() || null, yt = () => {
627
656
  let e = a().chatModels;
628
- if (!e?.length) return I;
657
+ if (!e?.length) return L;
629
658
  let t = /* @__PURE__ */ new Set();
630
659
  for (let n of e) {
631
660
  let e = X(typeof n == "string" ? n : n.id);
632
661
  e && t.add(e);
633
662
  }
634
663
  return t;
635
- }, _t = (e) => {
664
+ }, bt = (e) => {
636
665
  if (typeof e == "boolean") return e;
637
666
  let t = X(e)?.toLowerCase();
638
667
  return t ? t === "true" ? !0 : t === "false" ? !1 : null : null;
639
- }, vt = (e) => {
668
+ }, xt = (e) => {
640
669
  let t = e.req?.session?.user?.currentTenantId;
641
670
  return X(t);
642
- }, yt = (e) => {
671
+ }, St = (e) => {
643
672
  let t = e.req?.session?.user?.id;
644
673
  return X(t);
645
- }, bt = () => X(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", xt = (e) => ce("sha256").update(Buffer.from(e)).digest("hex"), St = (e) => {
674
+ }, Ct = () => X(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", wt = (e) => ae("sha256").update(Buffer.from(e)).digest("hex"), Tt = (e) => {
646
675
  let t = e.trim();
647
676
  if (!t) return null;
648
677
  let n;
@@ -655,36 +684,36 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
655
684
  return null;
656
685
  }
657
686
  }
658
- let r = ut.exec(n.pathname);
687
+ let r = dt.exec(n.pathname);
659
688
  if (!r) return null;
660
689
  let i = X(decodeURIComponent(r[1]));
661
690
  return i ? {
662
691
  fileId: i,
663
692
  uploadKey: X(n.searchParams.get("rb-upload-key"))
664
693
  } : null;
665
- }, Ct = async ({ ctx: e, fileId: t, uploadKey: n }) => {
666
- let r = vt(e);
694
+ }, Et = async ({ ctx: e, fileId: t, uploadKey: n }) => {
695
+ let r = xt(e);
667
696
  if (!r) throw Error("tenant_missing");
668
697
  let i;
669
698
  try {
670
- i = new le(t);
699
+ i = new oe(t);
671
700
  } catch {
672
701
  throw Error("invalid_file_id");
673
702
  }
674
- let a = (await E(r)).db;
703
+ let a = (await k(r)).db;
675
704
  if (!a) throw Error("filesystem_db_unavailable");
676
- let o = new O(a, { bucketName: bt() }), [s] = await o.find({ _id: i }).limit(1).toArray();
705
+ let o = new j(a, { bucketName: Ct() }), [s] = await o.find({ _id: i }).limit(1).toArray();
677
706
  if (!s) throw Error("file_not_found");
678
- let c = _t(s?.metadata?.isPublic) ?? !1, l = yt(e), u = X(s?.metadata?.userId), d = X(s?.metadata?.ownerKeyHash);
707
+ let c = bt(s?.metadata?.isPublic) ?? !1, l = St(e), u = X(s?.metadata?.userId), d = X(s?.metadata?.ownerKeyHash);
679
708
  if (!c) {
680
- let e = !!(l && u && l === u), t = !!(n && d && xt(n) === d);
709
+ let e = !!(l && u && l === u), t = !!(n && d && wt(n) === d);
681
710
  if (!e && !t) throw Error("unauthorized");
682
711
  }
683
712
  let f = X(s?.metadata?.mimeType), p = [], m = 0;
684
713
  return await new Promise((e, t) => {
685
714
  let n = o.openDownloadStream(i);
686
715
  n.on("data", (e) => {
687
- if (m += e.length, m > ct) {
716
+ if (m += e.length, m > lt) {
688
717
  n.destroy(/* @__PURE__ */ Error("attachment_too_large"));
689
718
  return;
690
719
  }
@@ -694,16 +723,16 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
694
723
  data: Buffer.concat(p, m),
695
724
  mimeType: f
696
725
  };
697
- }, wt = async (e, t) => {
726
+ }, Dt = async (e, t) => {
698
727
  let n = Array.isArray(t) ? t : [], r = [];
699
728
  for (let t of n) {
700
729
  if (!t || typeof t != "object" || !("role" in t) || t.role !== "user") continue;
701
730
  let n = Array.isArray(t.content) ? t.content : null;
702
731
  if (n) for (let t of n) {
703
732
  if (!t || typeof t != "object" || t.type !== "file" || typeof t.data != "string") continue;
704
- let n = St(t.data);
733
+ let n = Tt(t.data);
705
734
  n && r.push((async () => {
706
- let { data: r, mimeType: i } = await Ct({
735
+ let { data: r, mimeType: i } = await Et({
707
736
  ctx: e,
708
737
  ...n
709
738
  });
@@ -712,7 +741,7 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
712
741
  }
713
742
  }
714
743
  r.length > 0 && await Promise.all(r);
715
- }, Tt = (e) => {
744
+ }, Ot = (e) => {
716
745
  let t = Array.isArray(e) ? e : [];
717
746
  for (let e of t) {
718
747
  if (!e || typeof e != "object" || !("role" in e) || e.role !== "user") continue;
@@ -725,7 +754,7 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
725
754
  let i = X(n.filename) ?? X(n.name) ?? `attachment-${e + 1}`, a = n.data;
726
755
  if (r?.startsWith("text/") && a instanceof Uint8Array) {
727
756
  let n = (Buffer.isBuffer(a) ? a : Buffer.from(a)).toString("utf8");
728
- n.length > lt && (n = `${n.slice(0, lt)}\n\n[Truncated]`);
757
+ n.length > ut && (n = `${n.slice(0, ut)}\n\n[Truncated]`);
729
758
  let o = r === "text/csv" || i.toLowerCase().endsWith(".csv") ? "csv" : "";
730
759
  t[e] = {
731
760
  type: "text",
@@ -740,7 +769,7 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
740
769
  };
741
770
  }
742
771
  }
743
- }, Et = async (e, t, n) => {
772
+ }, kt = async (e, t, n) => {
744
773
  if (e.message?.role === "user") return it(e.message.parts);
745
774
  if (Array.isArray(e.messages)) {
746
775
  let t = null;
@@ -749,7 +778,7 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
749
778
  if (r?.role !== "user") continue;
750
779
  let i = it(r.parts);
751
780
  if (i) {
752
- if (Y(i)) return i;
781
+ if (st(i)) return i;
753
782
  t ??= i;
754
783
  }
755
784
  }
@@ -761,38 +790,38 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
761
790
  if (t.role !== "user") continue;
762
791
  let n = it(t.parts);
763
792
  if (n) {
764
- if (Y(n)) return n;
793
+ if (st(n)) return n;
765
794
  i ??= n;
766
795
  }
767
796
  }
768
797
  return i ?? "";
769
- }, Dt = (e) => {
798
+ }, At = (e) => {
770
799
  let t = Array.isArray(e.messages) && e.messages.length > 0 ? e.messages.at(-1) : e.message;
771
800
  return !t || t.role !== "user" ? "" : (Array.isArray(t.parts) ? t.parts : []).filter((e) => !!e && typeof e == "object" && !!e && "type" in e && "text" in e && e.type === "text" && typeof e.text == "string").map((e) => e.text).join("\n").trim();
772
- }, Ot = (e) => {
801
+ }, jt = (e) => {
773
802
  let t = e.id;
774
803
  return typeof t == "string" && t.trim() !== "" ? t : null;
775
- }, kt = (e) => {
804
+ }, Mt = (e) => {
776
805
  let t = e.selectedChatModel;
777
806
  return typeof t == "string" && t.trim() !== "" ? t : null;
778
- }, At = (e) => {
807
+ }, Nt = (e) => {
779
808
  let t = e.openaiReasoningEffort;
780
809
  return typeof t == "string" && t.trim() !== "" ? t.trim() : null;
781
- }, jt = (e) => {
810
+ }, Pt = (e) => {
782
811
  if (!e || typeof e != "object") return !1;
783
812
  let t = e.state, n = e.toolCallId;
784
813
  return typeof n == "string" && n.trim() !== "" && (t === "approval-responded" || t === "output-denied");
785
- }, Mt = (e) => {
814
+ }, Ft = (e) => {
786
815
  let t = Array.isArray(e.messages) ? e.messages : [];
787
- return t.length === 0 || t.at(-1)?.role === "user" ? !1 : t.some((e) => (Array.isArray(e?.parts) ? e.parts : []).some((e) => jt(e)));
788
- }, Nt = (e) => {
816
+ return t.length === 0 || t.at(-1)?.role === "user" ? !1 : t.some((e) => (Array.isArray(e?.parts) ? e.parts : []).some((e) => Pt(e)));
817
+ }, It = (e) => {
789
818
  let t = /* @__PURE__ */ new Map();
790
819
  for (let n of e) {
791
820
  let e = Array.isArray(n?.parts) ? n.parts : [];
792
- for (let n of e) jt(n) && t.set(n.toolCallId, n);
821
+ for (let n of e) Pt(n) && t.set(n.toolCallId, n);
793
822
  }
794
823
  return t;
795
- }, Pt = (e, t) => {
824
+ }, Lt = (e, t) => {
796
825
  let n = [];
797
826
  return {
798
827
  changedMessages: n,
@@ -815,21 +844,51 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
815
844
  return n.push(a), a;
816
845
  })
817
846
  };
818
- }, Ft = (e) => {
847
+ }, Rt = (e) => {
819
848
  if (!e || typeof e != "object" || !("createdAt" in e)) return null;
820
849
  let t = e.createdAt;
821
850
  if (typeof t != "string") return null;
822
851
  let n = new Date(t);
823
852
  return Number.isNaN(n.getTime()) ? null : n;
824
- }, It = (e) => ({
853
+ }, zt = (e) => ({
825
854
  latitude: null,
826
855
  longitude: null,
827
856
  city: null,
828
857
  country: null
829
- }), Lt = (e) => {
858
+ }), Bt = (e) => {
830
859
  let [t] = e.split("/");
831
860
  return t && t !== e ? t : "unknown";
832
- }, Z = (e) => typeof e == "number" && Number.isFinite(e) ? e : void 0, Rt = (e) => e instanceof Error && e.message.trim() ? e.message : "Unknown error", zt = (e) => e instanceof Error ? {
861
+ }, Vt = (e) => {
862
+ switch (Bt(e)) {
863
+ case "openai": return "OpenAI";
864
+ case "google": return "Google Gemini";
865
+ case "xai": return "xAI";
866
+ default: return "Provider";
867
+ }
868
+ }, Ht = (e) => {
869
+ switch (Bt(e)) {
870
+ case "openai": return "Set OPENAI_API_KEY and try again.";
871
+ case "google": return "Set GOOGLE_GENERATIVE_AI_API_KEY or GOOGLE_API_KEY and try again.";
872
+ case "xai": return "Set XAI_API_KEY and try again.";
873
+ default: return "Check the provider API key and try again.";
874
+ }
875
+ }, Ut = (e) => {
876
+ let t = a().chatModels ?? [];
877
+ for (let n of t) {
878
+ if (typeof n == "string") {
879
+ if (n === e) return e;
880
+ continue;
881
+ }
882
+ if (n.id !== e) continue;
883
+ let t = n.name;
884
+ return typeof t == "string" && t.trim() ? t.trim() : n.id;
885
+ }
886
+ let [, n] = e.split("/", 2);
887
+ return n || e;
888
+ }, Wt = (e) => typeof e.type == "string" ? !ht.has(e.type) : !1, Z = (e) => typeof e == "number" && Number.isFinite(e) ? e : void 0, Gt = (e) => e instanceof Error && e.message.trim() ? e.message : "Unknown error", Kt = (e, t) => {
889
+ let n = Gt(e).toLowerCase(), r = Vt(t);
890
+ return n.includes("api key") || n.includes("apikey") || n.includes("unauthorized") || n.includes("invalid authentication") || n.includes("401") ? `${r} API key is missing or invalid. ${Ht(t)}` : n.includes("quota") || n.includes("rate limit") || n.includes("rate_limit") || n.includes("billing") || n.includes("credit") || n.includes("429") ? `${r} could not process this request because of quota, rate limit, or billing limits. Check provider usage and billing, then try again.` : n.includes("tool approval") || n.includes("approvalid") || n.includes("approval id") || n.includes("tool call") || n.includes("tool result") || n.includes("missing tool") ? "The tool approval state for this message is out of date. Please retry the tool call." : n.includes("model not found") || n.includes("not found") || n.includes("unsupported model") || n.includes("404") ? `${r} could not use the selected model "${t}". Check the model configuration and provider access.` : "Something went wrong.";
891
+ }, qt = (e) => e instanceof Error ? {
833
892
  errorName: e.name,
834
893
  errorMessage: e.message,
835
894
  errorStack: e.stack,
@@ -837,12 +896,12 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
837
896
  } : { errorValue: e }, Q = (e, t, n) => {
838
897
  console.error(e, {
839
898
  ...n,
840
- ...zt(t)
899
+ ...qt(t)
841
900
  });
842
- }, Bt = (e) => ({
843
- chatId: Ot(e),
844
- selectedChatModel: kt(e)
845
- }), Vt = (e) => {
901
+ }, Jt = (e) => ({
902
+ chatId: jt(e),
903
+ selectedChatModel: Mt(e)
904
+ }), Yt = (e) => {
846
905
  let t = e && typeof e == "object" ? e : {}, n = t.inputTokenDetails && typeof t.inputTokenDetails == "object" ? t.inputTokenDetails : {}, r = t.outputTokenDetails && typeof t.outputTokenDetails == "object" ? t.outputTokenDetails : {};
847
906
  return {
848
907
  inputTokens: Z(t.inputTokens),
@@ -852,13 +911,13 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
852
911
  reasoningTokens: Z(r.reasoningTokens) ?? Z(t.reasoningTokens),
853
912
  rawUsage: Object.keys(t).length > 0 ? t.raw ?? t : void 0
854
913
  };
855
- }, Ht = () => ({
914
+ }, Xt = () => ({
856
915
  inputTokens: 0,
857
916
  outputTokens: 0,
858
917
  totalTokens: 0,
859
918
  cachedInputTokens: 0,
860
919
  reasoningTokens: 0
861
- }), Ut = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: r, mode: i }) => {
920
+ }), Zt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: r, mode: i }) => {
862
921
  try {
863
922
  return { workspaceId: X((await a().resolveUsageContext?.({
864
923
  ctx: e,
@@ -870,7 +929,7 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
870
929
  } catch (e) {
871
930
  return console.warn("Failed to resolve agent usage context.", e), { workspaceId: void 0 };
872
931
  }
873
- }, Wt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: r, mode: i }) => {
932
+ }, Qt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: r, mode: i }) => {
874
933
  let o = a().shouldGenerateChatTitle;
875
934
  if (!o) return !0;
876
935
  try {
@@ -885,19 +944,19 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
885
944
  return console.warn("Failed to resolve chat title generation setting.", e), !0;
886
945
  }
887
946
  }, $ = async ({ ctx: e, usageContext: t, agent: n, chatId: r, mode: i, feature: a, modelId: o, status: s, billable: c, usage: l, finishReason: u, error: d, startedAt: f, finishedAt: p = /* @__PURE__ */ new Date() }) => {
888
- let m = l ? Vt(l) : {}, h = {
889
- id: D(),
947
+ let m = l ? Yt(l) : {}, h = {
948
+ id: A(),
890
949
  workspaceId: t.workspaceId,
891
950
  agentId: n.id,
892
951
  chatId: r,
893
952
  mode: i,
894
953
  feature: a,
895
- provider: Lt(o),
954
+ provider: Bt(o),
896
955
  model: o,
897
956
  billable: c,
898
957
  status: s,
899
958
  finishReason: X(u) ?? void 0,
900
- errorMessage: d ? Rt(d) : void 0,
959
+ errorMessage: d ? Gt(d) : void 0,
901
960
  ...m,
902
961
  startedAt: f,
903
962
  finishedAt: p,
@@ -908,12 +967,12 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
908
967
  } catch (e) {
909
968
  console.error("Failed to save agents usage event.", e);
910
969
  }
911
- }, Gt = (e) => `agents-sdk:chat:${e}:stream`, Kt = async ({ ctx: e, chatId: t, selectedChatModel: n }) => await a().resolveAgent?.({
970
+ }, $t = (e) => `agents-sdk:chat:${e}:stream`, en = async ({ ctx: e, chatId: t, selectedChatModel: n }) => await a().resolveAgent?.({
912
971
  ctx: e,
913
972
  chatId: t,
914
973
  selectedChatModel: n
915
- }) ?? i(), qt = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
916
- let i = o(e), a = Gt(t), s = ee({
974
+ }) ?? i(), tn = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
975
+ let i = o(e), a = $t(t), s = S({
917
976
  chatId: t,
918
977
  abortWhenNoSubscribersMs: n === "headless" || r ? 0 : void 0
919
978
  });
@@ -941,83 +1000,83 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
941
1000
  });
942
1001
  }
943
1002
  };
944
- }, Jt = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
1003
+ }, nn = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
945
1004
  if (!n) return;
946
1005
  let i = o(e);
947
1006
  n.publish({
948
1007
  tenantId: i.tenantId,
949
1008
  userId: i.userId,
950
- channel: Gt(t),
1009
+ channel: $t(t),
951
1010
  payload: {
952
1011
  chatId: t,
953
1012
  message: r
954
1013
  }
955
1014
  });
956
- }, Yt = async ({ payload: e, ctx: i, mode: c = "interactive", streamTransport: d = null }) => {
957
- let p = Ot(e);
1015
+ }, rn = async ({ payload: e, ctx: i, mode: c = "interactive", streamTransport: d = null }) => {
1016
+ let p = jt(e);
958
1017
  if (!p) return r(i, "bad_request:api", "Parameter id is required.");
959
- let g = e, _ = kt(g), v = ht(process.env.PLAYWRIGHT), x = !ht(process.env.AGENT_SDK_LIVE_CHAT) && v || process.env.NODE_ENV === "test";
1018
+ let g = e, _ = Mt(g), v = vt(process.env.PLAYWRIGHT), x = !vt(process.env.AGENT_SDK_LIVE_CHAT) && v || process.env.NODE_ENV === "test";
960
1019
  if (!_) return r(i, "bad_request:api", "Parameter selectedChatModel is required.");
961
- if (_ === dt && (x = !0), _ !== dt && (!gt().has(_) || !me(_))) return r(i, "bad_request:api", `Unsupported selectedChatModel: "${_}".`);
962
- let ee = process.env.OPENAI_API_KEY, te = process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY, ie = process.env.XAI_API_KEY, S = de(_), C = fe(_), w = L(_), T = At(g), E = T && T !== "default" && T !== "off" ? T : null, ce = n(_);
963
- if (E && !ce.some((e) => e === E)) return r(i, "bad_request:api", `Unsupported reasoning effort "${E}" for selectedChatModel: "${_}".`);
964
- if (!x && S && !ee) return r(i, "bad_request:provider", "Missing OPENAI_API_KEY.");
965
- if (!x && C && !te) return r(i, "bad_request:provider", "Missing GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY).");
966
- if (!x && w && !ie) return r(i, "bad_request:provider", "Missing XAI_API_KEY.");
967
- if (!x && !S && !C && !w) return r(i, "bad_request:provider", `Unsupported selectedChatModel: "${_}".`);
968
- let O = await Kt({
1020
+ if (_ === ft && (x = !0), _ !== ft && (!yt().has(_) || !me(_))) return r(i, "bad_request:api", `Unsupported selectedChatModel: "${_}".`);
1021
+ let S = process.env.OPENAI_API_KEY, C = process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY, w = process.env.XAI_API_KEY, T = ue(_), E = de(_), D = fe(_), O = Nt(g), k = O && O !== "default" && O !== "off" ? O : null, ae = n(_);
1022
+ if (k && !ae.some((e) => e === k)) return r(i, "bad_request:api", `Unsupported reasoning effort "${k}" for selectedChatModel: "${_}".`);
1023
+ if (!x && T && !S) return r(i, "bad_request:provider", "Missing OPENAI_API_KEY.");
1024
+ if (!x && E && !C) return r(i, "bad_request:provider", "Missing GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY).");
1025
+ if (!x && D && !w) return r(i, "bad_request:provider", "Missing XAI_API_KEY.");
1026
+ if (!x && !T && !E && !D) return r(i, "bad_request:provider", `Unsupported selectedChatModel: "${_}".`);
1027
+ let j = await en({
969
1028
  ctx: i,
970
1029
  chatId: p,
971
1030
  selectedChatModel: _
972
- }), le = await a().resolveKnowledge?.({
1031
+ }), oe = await a().resolveKnowledge?.({
973
1032
  ctx: i,
974
1033
  chatId: p,
975
- agent: O,
1034
+ agent: j,
976
1035
  selectedChatModel: _
977
- }) ?? null, k = await Ut({
1036
+ }) ?? null, M = await Zt({
978
1037
  ctx: i,
979
1038
  chatId: p,
980
- agent: O,
1039
+ agent: j,
981
1040
  selectedChatModel: _,
982
1041
  mode: c
983
- }), A = await Wt({
1042
+ }), N = await Qt({
984
1043
  ctx: i,
985
1044
  chatId: p,
986
- agent: O,
1045
+ agent: j,
987
1046
  selectedChatModel: _,
988
1047
  mode: c
989
- }), ue = o(i), j = await l(i, p, { includeDeleted: !0 });
990
- if (j?.deletedAt) return r(i, "not_found:chat");
991
- j ? j.selectedChatModel !== _ && await u(i, {
1048
+ }), se = o(i), P = await l(i, p, { includeDeleted: !0 });
1049
+ if (P?.deletedAt) return r(i, "not_found:chat");
1050
+ P ? P.selectedChatModel !== _ && await u(i, {
992
1051
  chatId: p,
993
1052
  selectedChatModel: _
994
1053
  }) : await h(i, {
995
1054
  id: p,
996
1055
  createdAt: /* @__PURE__ */ new Date(),
997
- userId: ue.userId,
1056
+ userId: se.userId,
998
1057
  title: "",
999
1058
  isStreaming: !1,
1000
1059
  selectedChatModel: _,
1001
1060
  lastContext: null
1002
1061
  });
1003
- let M = g.message, N = typeof M?.id == "string" ? M.id : D(), P = Array.isArray(M?.parts) ? M?.parts : [];
1004
- if ((typeof M?.role == "string" ? M.role : null) === "user") {
1062
+ let F = g.message, ce = typeof F?.id == "string" ? F.id : A(), le = Array.isArray(F?.parts) ? F?.parts : [];
1063
+ if ((typeof F?.role == "string" ? F.role : null) === "user") {
1005
1064
  let e = /* @__PURE__ */ new Date();
1006
1065
  await f(i, [{
1007
- id: N,
1066
+ id: ce,
1008
1067
  chatId: p,
1009
1068
  role: "user",
1010
- parts: P,
1069
+ parts: le,
1011
1070
  attachments: [],
1012
1071
  createdAt: e
1013
- }]), Jt({
1072
+ }]), nn({
1014
1073
  ctx: i,
1015
1074
  chatId: p,
1016
1075
  streamTransport: d,
1017
1076
  message: {
1018
- id: N,
1077
+ id: ce,
1019
1078
  role: "user",
1020
- parts: P,
1079
+ parts: le,
1021
1080
  metadata: { createdAt: e.toISOString() }
1022
1081
  }
1023
1082
  });
@@ -1027,15 +1086,15 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1027
1086
  chatId: p,
1028
1087
  isStreaming: !0
1029
1088
  });
1030
- let e = qt({
1089
+ let e = tn({
1031
1090
  ctx: i,
1032
1091
  chatId: p,
1033
1092
  mode: c,
1034
1093
  streamTransport: d
1035
1094
  });
1036
1095
  try {
1037
- if (A) {
1038
- let t = Y(await Et(g, i, p)), n = await l(i, p);
1096
+ if (N) {
1097
+ let t = st(await kt(g, i, p)), n = await l(i, p);
1039
1098
  n && rt(n.title) && t && t !== n.title && (await s(i, {
1040
1099
  chatId: p,
1041
1100
  title: t
@@ -1045,8 +1104,8 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1045
1104
  transient: !0
1046
1105
  }));
1047
1106
  }
1048
- let t = D();
1049
- v && !e.abortController.signal.aborted && await pt(600), e.publishJson({
1107
+ let t = A();
1108
+ v && !e.abortController.signal.aborted && await gt(600), e.publishJson({
1050
1109
  type: "start",
1051
1110
  messageId: t
1052
1111
  });
@@ -1055,18 +1114,18 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1055
1114
  type: "text-start",
1056
1115
  id: n
1057
1116
  });
1058
- let r = Dt(g), a = r ? `Echo: ${r}` : "Hello from agents-sdk", o = Date.now(), u = a.split(/(\s+)/).filter((e) => e.length > 0);
1117
+ let r = At(g), a = r ? `Echo: ${r}` : "Hello from agents-sdk", o = Date.now(), u = a.split(/(\s+)/).filter((e) => e.length > 0);
1059
1118
  for (let t of u) {
1060
1119
  if (e.abortController.signal.aborted) break;
1061
1120
  e.publishJson({
1062
1121
  type: "text-delta",
1063
1122
  id: n,
1064
1123
  delta: t
1065
- }), await pt(v ? 120 : 80);
1124
+ }), await gt(v ? 120 : 80);
1066
1125
  }
1067
1126
  if (v && !e.abortController.signal.aborted) {
1068
1127
  let e = Date.now() - o, t = 1200;
1069
- e < t && await pt(t - e);
1128
+ e < t && await gt(t - e);
1070
1129
  }
1071
1130
  return e.abortController.signal.aborted ? {} : (e.publishJson({
1072
1131
  type: "text-end",
@@ -1086,24 +1145,24 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1086
1145
  createdAt: /* @__PURE__ */ new Date()
1087
1146
  }]), await $({
1088
1147
  ctx: i,
1089
- usageContext: k,
1090
- agent: O,
1148
+ usageContext: M,
1149
+ agent: j,
1091
1150
  chatId: p,
1092
1151
  mode: c,
1093
1152
  feature: "chat",
1094
1153
  modelId: _,
1095
1154
  status: "success",
1096
1155
  billable: !1,
1097
- usage: Ht(),
1156
+ usage: Xt(),
1098
1157
  finishReason: "stop",
1099
1158
  startedAt: new Date(o)
1100
1159
  }), {});
1101
1160
  } finally {
1102
- await mt(i, p);
1161
+ await _t(i, p);
1103
1162
  }
1104
1163
  }
1105
- let F = It(i), I = Mt(g);
1106
- if (Array.isArray(g.messages) && !I) {
1164
+ let I = zt(i), L = Ft(g);
1165
+ if (Array.isArray(g.messages) && !L) {
1107
1166
  let e = g.messages.flatMap((e) => {
1108
1167
  let t = typeof e?.id == "string" ? e.id : null, n = typeof e?.role == "string" ? e.role : null, r = Array.isArray(e?.parts) ? e.parts : [];
1109
1168
  return !t || !n ? [] : [{
@@ -1112,17 +1171,17 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1112
1171
  role: n,
1113
1172
  parts: r,
1114
1173
  attachments: [],
1115
- createdAt: Ft(e?.metadata) ?? /* @__PURE__ */ new Date()
1174
+ createdAt: Rt(e?.metadata) ?? /* @__PURE__ */ new Date()
1116
1175
  }];
1117
1176
  });
1118
1177
  e.length > 0 && await f(i, e);
1119
1178
  }
1120
1179
  let R;
1121
- if (Array.isArray(g.messages) && g.messages.length > 0 && I) {
1180
+ if (Array.isArray(g.messages) && g.messages.length > 0 && L) {
1122
1181
  let e = await m(i, p);
1123
1182
  if (e.length === 0) R = g.messages;
1124
1183
  else {
1125
- let { changedMessages: t, updatedMessages: n } = Pt(e, Nt(g.messages));
1184
+ let { changedMessages: t, updatedMessages: n } = Lt(e, It(g.messages));
1126
1185
  t.length > 0 && await f(i, t), R = n.map((e) => ({
1127
1186
  id: e.id,
1128
1187
  role: e.role,
@@ -1136,20 +1195,20 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1136
1195
  parts: e.parts,
1137
1196
  metadata: { createdAt: e.createdAt.toISOString() }
1138
1197
  }));
1139
- let z = I ? {
1198
+ let z = L ? {
1140
1199
  messages: R,
1141
- lastContext: j?.lastContext ?? null,
1200
+ lastContext: P?.lastContext ?? null,
1142
1201
  lastContextChanged: !1
1143
1202
  } : await He({
1144
1203
  ctx: i,
1145
1204
  chatId: p,
1146
- agent: O,
1205
+ agent: j,
1147
1206
  selectedChatModel: _,
1148
1207
  mode: c,
1149
1208
  messages: R,
1150
- lastContext: j?.lastContext ?? null
1209
+ lastContext: P?.lastContext ?? null
1151
1210
  });
1152
- if (!I && z.lastContextChanged) try {
1211
+ if (!L && z.lastContextChanged) try {
1153
1212
  await b(i, {
1154
1213
  chatId: p,
1155
1214
  lastContext: z.lastContext
@@ -1162,14 +1221,14 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1162
1221
  chatId: p,
1163
1222
  isStreaming: !0
1164
1223
  });
1165
- let V = qt({
1224
+ let V = tn({
1166
1225
  ctx: i,
1167
1226
  chatId: p,
1168
1227
  mode: c,
1169
1228
  streamTransport: d
1170
1229
  }), H = "", U = "";
1171
- if (A) try {
1172
- H = await Et(g, i, p), U = Y(H);
1230
+ if (N) try {
1231
+ H = await kt(g, i, p), U = st(H);
1173
1232
  let e = await l(i, p);
1174
1233
  e && rt(e.title) && U && U !== e.title && (await s(i, {
1175
1234
  chatId: p,
@@ -1183,40 +1242,40 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1183
1242
  Q("Failed to prepare agent chat title.", e, {
1184
1243
  chatId: p,
1185
1244
  selectedChatModel: _,
1186
- agentId: O.id,
1245
+ agentId: j.id,
1187
1246
  mode: c
1188
1247
  }), V.publishJson({
1189
1248
  type: "error",
1190
1249
  errorText: "Something went wrong."
1191
1250
  }), V.publishDone();
1192
1251
  try {
1193
- await mt(i, p);
1252
+ await _t(i, p);
1194
1253
  } catch (e) {
1195
1254
  Q("Failed to update chat streaming state.", e, {
1196
1255
  chatId: p,
1197
1256
  selectedChatModel: _,
1198
- agentId: O.id,
1257
+ agentId: j.id,
1199
1258
  mode: c
1200
1259
  });
1201
1260
  }
1202
1261
  return {};
1203
1262
  }
1204
- A && H && U && ee && (async () => {
1263
+ N && H && U && S && (async () => {
1205
1264
  let e = /* @__PURE__ */ new Date();
1206
1265
  try {
1207
- let { text: t } = await ae({
1266
+ let { text: t } = await ne({
1208
1267
  model: ge(),
1209
1268
  system: xe,
1210
1269
  prompt: H,
1211
1270
  onFinish: async (t) => {
1212
1271
  await $({
1213
1272
  ctx: i,
1214
- usageContext: k,
1215
- agent: O,
1273
+ usageContext: M,
1274
+ agent: j,
1216
1275
  chatId: p,
1217
1276
  mode: c,
1218
1277
  feature: "title",
1219
- modelId: ft,
1278
+ modelId: pt,
1220
1279
  status: "success",
1221
1280
  billable: !0,
1222
1281
  usage: t.totalUsage ?? t.usage,
@@ -1239,12 +1298,12 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1239
1298
  } catch (t) {
1240
1299
  await $({
1241
1300
  ctx: i,
1242
- usageContext: k,
1243
- agent: O,
1301
+ usageContext: M,
1302
+ agent: j,
1244
1303
  chatId: p,
1245
1304
  mode: c,
1246
1305
  feature: "title",
1247
- modelId: ft,
1306
+ modelId: pt,
1248
1307
  status: "error",
1249
1308
  billable: !1,
1250
1309
  error: t,
@@ -1252,18 +1311,18 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1252
1311
  }), console.warn("Failed to generate chat title.", t);
1253
1312
  }
1254
1313
  })();
1255
- let ve = re({
1314
+ let ve = te({
1256
1315
  originalMessages: R,
1257
1316
  onError: (e) => (Q("Agent chat stream failed.", e, {
1258
1317
  chatId: p,
1259
1318
  selectedChatModel: _,
1260
- agentId: O.id,
1319
+ agentId: j.id,
1261
1320
  mode: c
1262
- }), "Something went wrong."),
1321
+ }), Kt(e, _)),
1263
1322
  onFinish: async ({ responseMessage: e }) => {
1264
1323
  let t = Array.isArray(e.parts) ? e.parts : [];
1265
1324
  await f(i, [{
1266
- id: e.id ?? D(),
1325
+ id: e.id ?? A(),
1267
1326
  chatId: p,
1268
1327
  role: e.role ?? "assistant",
1269
1328
  parts: t,
@@ -1275,7 +1334,7 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1275
1334
  let t = Xe({
1276
1335
  ctx: i,
1277
1336
  dataStream: e,
1278
- requestHints: F
1337
+ requestHints: I
1279
1338
  }), n = [
1280
1339
  "getWeather",
1281
1340
  "createDocument",
@@ -1289,11 +1348,11 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1289
1348
  "editDocument",
1290
1349
  "updateDocument",
1291
1350
  "requestSuggestions"
1292
- ], o = pe(_), s = o ? [] : S ? n : r, l = t, u = s, d = await a().resolveTools?.({
1351
+ ], o = pe(_), s = o ? [] : T ? n : r, l = t, u = s, d = await a().resolveTools?.({
1293
1352
  ctx: i,
1294
1353
  dataStream: e,
1295
- requestHints: F,
1296
- agent: O,
1354
+ requestHints: I,
1355
+ agent: j,
1297
1356
  selectedChatModel: _,
1298
1357
  availableTools: t,
1299
1358
  defaultActiveTools: s
@@ -1301,9 +1360,9 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1301
1360
  d && (l = d.tools, u = d.activeTools ?? Object.keys(d.tools)), u = nt({
1302
1361
  activeTools: u,
1303
1362
  availableTools: l,
1304
- userText: Dt(g)
1363
+ userText: At(g)
1305
1364
  });
1306
- let f = await ne(B.map((e) => ({
1365
+ let f = await ee(B.map((e) => ({
1307
1366
  role: e?.role,
1308
1367
  parts: e?.parts,
1309
1368
  metadata: e?.metadata
@@ -1311,17 +1370,17 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1311
1370
  tools: l,
1312
1371
  ignoreIncompleteToolCalls: !0
1313
1372
  });
1314
- await wt(i, f), S && Tt(f);
1373
+ await Dt(i, f), T && Ot(f);
1315
1374
  let m = typeof g.openaiReasoningSummary == "string" ? g.openaiReasoningSummary : null, h;
1316
- S && E ? h = { openai: {
1317
- reasoningEffort: E,
1375
+ T && k ? h = { openai: {
1376
+ reasoningEffort: k,
1318
1377
  reasoningSummary: m ?? void 0
1319
- } } : w && o && E && (h = { xai: { reasoningEffort: E } });
1378
+ } } : D && o && k && (h = { xai: { reasoningEffort: k } });
1320
1379
  let v = !1, y = /* @__PURE__ */ new Date(), b = async ({ status: e, usage: t, finishReason: n, error: r }) => {
1321
1380
  v || (v = !0, await $({
1322
1381
  ctx: i,
1323
- usageContext: k,
1324
- agent: O,
1382
+ usageContext: M,
1383
+ agent: j,
1325
1384
  chatId: p,
1326
1385
  mode: c,
1327
1386
  feature: "chat",
@@ -1333,44 +1392,82 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1333
1392
  error: r,
1334
1393
  startedAt: y
1335
1394
  }));
1336
- }, x = se({
1337
- model: he(_),
1338
- system: _e({
1339
- selectedChatModel: _,
1340
- requestHints: F,
1341
- agentInstructions: O.instructions,
1342
- knowledge: le
1343
- }),
1344
- messages: f,
1345
- tools: l,
1346
- stopWhen: oe(5),
1347
- abortSignal: V.abortController.signal,
1348
- providerOptions: h,
1349
- activeTools: u,
1350
- onFinish: async (e) => {
1351
- await b({
1352
- status: "success",
1353
- usage: e.totalUsage ?? e.usage,
1354
- finishReason: e.finishReason
1355
- });
1356
- },
1357
- onError: async (e) => {
1358
- await b({
1359
- status: "error",
1360
- error: e?.error ?? e
1361
- });
1362
- },
1363
- onAbort: async (e) => {
1364
- await b({
1365
- status: "aborted",
1366
- usage: e?.totalUsage ?? e?.usage,
1367
- finishReason: e?.finishReason
1395
+ }, x = Ut(_), S = !1, C, te = () => {
1396
+ C &&= (clearTimeout(C), void 0);
1397
+ }, w = (t, n) => {
1398
+ S && t !== "thinking" || e.write({
1399
+ type: "data-waiting-status",
1400
+ data: {
1401
+ phase: t,
1402
+ message: n,
1403
+ modelId: _,
1404
+ modelName: x
1405
+ },
1406
+ transient: !0
1407
+ });
1408
+ }, ne = () => {
1409
+ S || (S = !0, te(), w("thinking", "Thinking..."));
1410
+ }, E = () => {
1411
+ S = !0, te();
1412
+ };
1413
+ w("waiting", "Waiting..."), C = setTimeout(() => {
1414
+ w("still-waiting", "Still waiting...");
1415
+ }, mt);
1416
+ let O = (() => {
1417
+ try {
1418
+ return ie({
1419
+ model: he(_),
1420
+ system: _e({
1421
+ selectedChatModel: _,
1422
+ requestHints: I,
1423
+ agentInstructions: j.instructions,
1424
+ knowledge: oe
1425
+ }),
1426
+ messages: f,
1427
+ tools: l,
1428
+ stopWhen: re(5),
1429
+ abortSignal: V.abortController.signal,
1430
+ providerOptions: h,
1431
+ activeTools: u,
1432
+ onFinish: async (e) => {
1433
+ E(), await b({
1434
+ status: "success",
1435
+ usage: e.totalUsage ?? e.usage,
1436
+ finishReason: e.finishReason
1437
+ });
1438
+ },
1439
+ onError: async (e) => {
1440
+ E();
1441
+ let t = e?.error ?? e;
1442
+ Q("Agent model stream failed.", t, {
1443
+ chatId: p,
1444
+ selectedChatModel: _,
1445
+ agentId: j.id,
1446
+ mode: c
1447
+ }), await b({
1448
+ status: "error",
1449
+ error: t
1450
+ });
1451
+ },
1452
+ onAbort: async (e) => {
1453
+ E(), await b({
1454
+ status: "aborted",
1455
+ usage: e?.totalUsage ?? e?.usage,
1456
+ finishReason: e?.finishReason
1457
+ });
1458
+ },
1459
+ onChunk: ({ chunk: e }) => {
1460
+ Wt(e) && ne();
1461
+ }
1368
1462
  });
1463
+ } catch (e) {
1464
+ throw E(), e;
1369
1465
  }
1370
- });
1371
- e.merge(x.toUIMessageStream({
1466
+ })();
1467
+ e.merge(O.toUIMessageStream({
1372
1468
  originalMessages: R,
1373
- sendReasoning: o || !!(S && E)
1469
+ onError: (e) => Kt(e, _),
1470
+ sendReasoning: o || !!(T && k)
1374
1471
  }));
1375
1472
  }
1376
1473
  });
@@ -1415,51 +1512,51 @@ var ct = 1024 * 1024 * 20, lt = 1e5, ut = /^\/api\/rb\/files\/([^/]+)\/?$/, dt =
1415
1512
  Q("Agent chat runtime stream failed.", e, {
1416
1513
  chatId: p,
1417
1514
  selectedChatModel: _,
1418
- agentId: O.id,
1515
+ agentId: j.id,
1419
1516
  mode: c
1420
1517
  }), V.publishJson({
1421
1518
  type: "error",
1422
- errorText: "Something went wrong."
1519
+ errorText: Kt(e, _)
1423
1520
  }), V.publishDone();
1424
1521
  } finally {
1425
1522
  await n?.(), e?.();
1426
1523
  try {
1427
- await mt(i, p);
1524
+ await _t(i, p);
1428
1525
  } catch (e) {
1429
1526
  Q("Failed to update chat streaming state.", e, {
1430
1527
  chatId: p,
1431
1528
  selectedChatModel: _,
1432
- agentId: O.id,
1529
+ agentId: j.id,
1433
1530
  mode: c
1434
1531
  });
1435
1532
  }
1436
1533
  }
1437
1534
  })(), {};
1438
- }, Xt = async (e, t) => {
1535
+ }, an = async (e, t) => {
1439
1536
  try {
1440
- return await Yt({
1537
+ return await rn({
1441
1538
  payload: e,
1442
1539
  ctx: t,
1443
1540
  mode: "interactive"
1444
1541
  });
1445
1542
  } catch (n) {
1446
1543
  return Q("Agent chat request failed.", n, {
1447
- ...Bt(e),
1544
+ ...Jt(e),
1448
1545
  mode: "interactive"
1449
1546
  }), r(t, "internal:api");
1450
1547
  }
1451
- }, Zt = async (e, t) => {
1548
+ }, on = async (e, t) => {
1452
1549
  let n = t.req.query.id, i = Array.isArray(n) ? n[0] : n;
1453
1550
  return typeof i != "string" || i.trim() === "" ? r(t, "bad_request:api") : g(t, i);
1454
- }, Qt = (t) => {
1455
- t.get(st, (async (t, n) => {
1551
+ }, sn = (t) => {
1552
+ t.get(ct, (async (t, n) => {
1456
1553
  let i = n.req.query.id, a = Array.isArray(i) ? i[0] : i;
1457
1554
  if (typeof a != "string" || a.trim() === "") return r(n, "bad_request:api", "Parameter id is required.");
1458
1555
  let o = await l(n, a);
1459
1556
  if (!o) return r(n, "not_found:chat");
1460
1557
  let s = x(a);
1461
1558
  return e(o) && (!s || s.isDone) && (o = await d(n, o)), o;
1462
- })), t.post(st, Xt), t.delete(st, Zt);
1559
+ })), t.post(ct, an), t.delete(ct, on);
1463
1560
  };
1464
1561
  //#endregion
1465
- export { Qt as default, Yt as runAgentLoop };
1562
+ export { sn as default, rn as runAgentLoop };