@rpcbase/agents-sdk 0.9.0 → 0.11.0

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