@rpcbase/agents-sdk 0.2.0 → 0.3.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 (82) hide show
  1. package/dist/agents-sdk.css +1 -1
  2. package/dist/api/chat/handler.d.ts.map +1 -1
  3. package/dist/api/chat/messages/handler.d.ts.map +1 -1
  4. package/dist/api/chat/messages/trailing/handler.d.ts.map +1 -1
  5. package/dist/api/chat/runtimeConfig.d.ts +11 -0
  6. package/dist/api/chat/runtimeConfig.d.ts.map +1 -1
  7. package/dist/api/chatDb.d.ts +35 -1
  8. package/dist/api/chatDb.d.ts.map +1 -1
  9. package/dist/api/chatStore.d.ts +11 -2
  10. package/dist/api/chatStore.d.ts.map +1 -1
  11. package/dist/api/session/current/handler.d.ts +4 -0
  12. package/dist/api/session/current/handler.d.ts.map +1 -0
  13. package/dist/api/session/current/index.d.ts +11 -0
  14. package/dist/api/session/current/index.d.ts.map +1 -0
  15. package/dist/{chatDb-CpCFaAxK.js → chatDb-CcAjAGX7.js} +76 -61
  16. package/dist/{chatDb-hVHCr0j0.js → chatDb-DfmUbQT2.js} +76 -61
  17. package/dist/client-routes.browser.js +9 -8
  18. package/dist/client-routes.js +9 -8
  19. package/dist/components/ai-elements/model-selector.d.ts.map +1 -1
  20. package/dist/components/chat.d.ts.map +1 -1
  21. package/dist/components/multimodal-input.d.ts.map +1 -1
  22. package/dist/components/sidebar-history.d.ts.map +1 -1
  23. package/dist/components/ui/dialog.d.ts +4 -1
  24. package/dist/components/ui/dialog.d.ts.map +1 -1
  25. package/dist/{data-stream-handler-DMKVEvOY.js → data-stream-handler-CTBOlLdZ.js} +109 -95
  26. package/dist/{data-stream-handler-6o0tw3-M.js → data-stream-handler-LGFXl3Kj.js} +116 -102
  27. package/dist/{handler-BcbiHqzs.js → handler-5D9tLMpX.js} +418 -274
  28. package/dist/{handler-CwGQ3dV4.js → handler-B6kVyUoS.js} +1 -1
  29. package/dist/{handler-B3iF4jS4.js → handler-BKT8Hl0a.js} +1 -1
  30. package/dist/{handler-CzKTKfwA.js → handler-BLG0AYVC.js} +1 -1
  31. package/dist/handler-BQZNf9EG.js +21 -0
  32. package/dist/{handler-Bb3YEDwz.js → handler-BUvspcpX.js} +1 -1
  33. package/dist/handler-BdCGoVUM.js +21 -0
  34. package/dist/{handler-CZ-GUuYr.js → handler-BeWk8pDD.js} +1 -1
  35. package/dist/handler-BgY0anAs.js +19 -0
  36. package/dist/{handler-BU60I9Tt.js → handler-BqHuBA6Q.js} +1 -1
  37. package/dist/{handler-C2MJfgeU.js → handler-CEk1hut1.js} +1 -1
  38. package/dist/{handler-DRk4qlh0.js → handler-CGV7uuUA.js} +1 -1
  39. package/dist/{handler-DBFa5_B9.js → handler-CKmHOFMG.js} +1 -1
  40. package/dist/{handler-ImeP5Thm.js → handler-ClWOGjB_.js} +455 -311
  41. package/dist/{handler-Dmw-3E9n.js → handler-PkV1nrcU.js} +1 -1
  42. package/dist/handler-dVlpopfq.js +21 -0
  43. package/dist/handler-klwfX3CY.js +21 -0
  44. package/dist/handler-mbDBRYl8.js +19 -0
  45. package/dist/index.browser.js +1 -1
  46. package/dist/index.js +1 -1
  47. package/dist/lib/ai/openai-reasoning.d.ts +1 -1
  48. package/dist/lib/ai/openai-reasoning.d.ts.map +1 -1
  49. package/dist/lib/db/schema.d.ts +29 -0
  50. package/dist/lib/db/schema.d.ts.map +1 -1
  51. package/dist/loaders/chatLoader.d.ts +1 -0
  52. package/dist/loaders/chatLoader.d.ts.map +1 -1
  53. package/dist/models/RBAgentsChatThread.d.ts +3 -0
  54. package/dist/models/RBAgentsChatThread.d.ts.map +1 -1
  55. package/dist/models/RBAgentsUsageEvent.d.ts +45 -0
  56. package/dist/models/RBAgentsUsageEvent.d.ts.map +1 -0
  57. package/dist/models/index.browser.d.ts +4 -0
  58. package/dist/models/index.browser.d.ts.map +1 -1
  59. package/dist/models/index.d.ts +34 -0
  60. package/dist/models/index.d.ts.map +1 -1
  61. package/dist/models.browser.js +35 -3
  62. package/dist/models.js +204 -4
  63. package/dist/{openai-reasoning-ARz6ZvZ_.js → openai-reasoning-CLjhz1V1.js} +1 -1
  64. package/dist/{openai-reasoning-jbPa-xup.js → openai-reasoning-kFq60GX9.js} +1 -1
  65. package/dist/pages/ChatPage.d.ts.map +1 -1
  66. package/dist/routes.browser.js +12 -11
  67. package/dist/routes.js +12 -11
  68. package/dist/runtime.d.ts +2 -2
  69. package/dist/runtime.d.ts.map +1 -1
  70. package/dist/runtime.js +1 -1
  71. package/dist/tailwind-source.js +1 -1
  72. package/package.json +1 -1
  73. package/dist/handler-B4PUL3Fm.js +0 -21
  74. package/dist/handler-DAjf6ro0.js +0 -19
  75. package/dist/handler-DN-H4zmz.js +0 -19
  76. package/dist/handler-Df8dOV-8.js +0 -21
  77. /package/dist/{handler-CxfBBYhN.js → handler-BdEE0--D.js} +0 -0
  78. /package/dist/{handler-CzHg9puj.js → handler-BdXUC9Rg.js} +0 -0
  79. /package/dist/{handler-_UsjVWVA.js → handler-D74Wi6e9.js} +0 -0
  80. /package/dist/{handler-Ct7ZyGSn.js → handler-D752oOcY.js} +0 -0
  81. /package/dist/{handler-CSLr0jTM.js → handler-hV65_Dui.js} +0 -0
  82. /package/dist/{handler-oJ8qxBLd.js → handler-jpHBMoww.js} +0 -0
@@ -1,64 +1,64 @@
1
- import { r as e } from "./openai-reasoning-ARz6ZvZ_.js";
1
+ import { r as e } from "./openai-reasoning-kFq60GX9.js";
2
2
  import { t } from "./apiErrors-CFUx-UrE.js";
3
3
  import { i as n, r, t as i } from "./chatCtx-DSgD1fix.js";
4
- import { _ as a, a as o, g as s, h as c, l, m as u, n as d, p as f, s as p, v as m } from "./chatDb-CpCFaAxK.js";
5
- import { n as h, t as g } from "./resumableSse-BRFonw_y.js";
6
- import { Output as _, convertToModelMessages as ee, createUIMessageStream as te, extractReasoningMiddleware as v, generateText as ne, smoothStream as y, stepCountIs as re, streamObject as b, streamText as x, tool as S, wrapLanguageModel as C } from "ai";
7
- import { getTenantFilesystemDb as w } from "@rpcbase/db";
8
- import { createHash as T, randomUUID as E } from "node:crypto";
9
- import { GridFSBucket as D, ObjectId as O } from "mongodb";
4
+ import { _ as a, a as o, b as s, g as c, h as l, l as u, m as d, n as f, p, s as m, v as h, y as g } from "./chatDb-CcAjAGX7.js";
5
+ import { n as _, t as v } from "./resumableSse-BRFonw_y.js";
6
+ import { Output as y, convertToModelMessages as ee, createUIMessageStream as b, extractReasoningMiddleware as x, generateText as te, smoothStream as ne, stepCountIs as re, streamObject as S, streamText as C, tool as w, wrapLanguageModel as ie } from "ai";
7
+ import { getTenantFilesystemDb as T } from "@rpcbase/db";
8
+ import { createHash as E, randomUUID as D } from "node:crypto";
9
+ import { GridFSBucket as O, ObjectId as ae } from "mongodb";
10
10
  import { createGoogleGenerativeAI as k } from "@ai-sdk/google";
11
11
  import { openai as A } from "@ai-sdk/openai";
12
- import { createXai as ie } from "@ai-sdk/xai";
13
- import { z as j } from "zod";
12
+ import { createXai as j } from "@ai-sdk/xai";
13
+ import { z as M } from "zod";
14
14
  //#region src/api/chat/models.ts
15
- var M = /-thinking$/, N = "openai/", P = "google/", F = "xai/", ae = new Set([
15
+ var N = /-thinking$/, P = "openai/", F = "google/", I = "xai/", oe = new Set([
16
16
  "openai/gpt-5.4-mini",
17
17
  "openai/gpt-5.5",
18
18
  "google/gemini-3.5-flash",
19
19
  "xai/grok-4.3-thinking"
20
- ]), I = (e) => e.startsWith(N), L = (e) => e.startsWith(P), R = (e) => e.startsWith(F), z = (e) => e.endsWith("-thinking"), B = ie({
20
+ ]), se = (e) => e.startsWith(P), ce = (e) => e.startsWith(F), le = (e) => e.startsWith(I), L = (e) => e.endsWith("-thinking"), R = j({
21
21
  baseURL: process.env.XAI_BASE_URL ?? "https://api.x.ai/v1",
22
22
  apiKey: process.env.XAI_API_KEY
23
- }), V = k({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY }), oe = (e) => {
24
- if (I(e)) return A.responses(e.slice(N.length));
25
- if (L(e)) {
26
- let t = e.slice(P.length).replace(M, ""), n = V.chat(t);
27
- return z(e) ? C({
23
+ }), z = k({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY }), ue = (e) => {
24
+ if (se(e)) return A.responses(e.slice(P.length));
25
+ if (ce(e)) {
26
+ let t = e.slice(F.length).replace(N, ""), n = z.chat(t);
27
+ return L(e) ? ie({
28
28
  model: n,
29
- middleware: v({ tagName: "thinking" })
29
+ middleware: x({ tagName: "thinking" })
30
30
  }) : n;
31
31
  }
32
- if (R(e)) {
33
- let t = e.slice(F.length).replace(M, "");
34
- return z(e) ? B.responses(t) : B.chat(t);
32
+ if (le(e)) {
33
+ let t = e.slice(I.length).replace(N, "");
34
+ return L(e) ? R.responses(t) : R.chat(t);
35
35
  }
36
36
  throw Error(`Unsupported modelId: ${e}`);
37
- }, se = () => A.chat("gpt-5.4-mini"), H = () => A.chat(process.env.AGENT_SDK_ARTIFACT_MODEL ?? "gpt-5.4-mini"), U = "\nArtifacts is a special user interface mode that helps users with writing, editing, and other content creation tasks. When artifact is open, it is on the right side of the screen, while the conversation is on the left side. When creating, editing, or updating documents, changes are reflected in real-time on the artifacts and visible to the user.\n\nWhen asked to write code, always use artifacts. When writing code, specify the language in the backticks, e.g. ```python`code here```. The default language is Python. Other languages are not yet supported, so let the user know if they request a different language.\n\nCritical rules:\n- Only call one artifact tool per response.\n- Do not update or edit a document immediately after creating it. Wait for user feedback or an explicit request to modify it.\n- After creating, editing, or updating an artifact, do not repeat the full artifact content in chat. The user can already see it.\n\nThis is a guide for using artifacts tools: `createDocument`, `editDocument`, `updateDocument`, and `requestSuggestions`, which render content on artifacts beside the conversation.\n\n**When to use `createDocument`:**\n- For substantial content (>10 lines) or code\n- For content users will likely save/reuse (emails, code, essays, etc.)\n- When explicitly requested to create a document\n- For when content contains a single code snippet\n- Use kind \"code\" for programming, \"text\" for writing, and \"sheet\" for tabular/CSV data\n\n**When NOT to use `createDocument`:**\n- For informational/explanatory content\n- For conversational responses\n- When asked to keep it in chat\n\n**Using `editDocument`:**\n- Prefer this for targeted edits to an existing artifact\n- For scripts: fixing bugs, adding/removing lines, renaming variables, adding logs\n- For documents: fixing typos, rewording paragraphs, inserting or replacing sections\n- Provide an exact `old_string` and `new_string`\n- Include enough surrounding context in `old_string` to make the match unique\n- Use `replace_all: true` only for deliberate repeated replacements, like renaming a variable everywhere\n\n**Using `updateDocument`:**\n- Default to full document rewrites for major changes\n- Use `editDocument` instead for specific, isolated changes\n- Follow user instructions for which parts to modify\n\n**When NOT to use `editDocument` or `updateDocument`:**\n- Immediately after creating a document\n- Without an explicit user request to modify the artifact\n\n**Using `requestSuggestions`:**\n- ONLY use when the user explicitly asks for suggestions on an existing document\n- Requires a valid document ID from a previously created document\n- Never use for general questions or information requests\n", W = "You are a friendly assistant! Keep your responses concise and helpful.\n\nWhen asked to write, create, or help with something, just do it directly. Don't ask clarifying questions unless absolutely necessary - make reasonable assumptions and proceed with the task.", ce = (e) => `\
37
+ }, de = () => 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
38
  About the origin of user's request:
39
39
  - lat: ${e.latitude ?? "unknown"}
40
40
  - lon: ${e.longitude ?? "unknown"}
41
41
  - city: ${e.city ?? "unknown"}
42
42
  - country: ${e.country ?? "unknown"}
43
- `, le = ({ selectedChatModel: e, requestHints: t, agentInstructions: n, knowledge: r }) => {
44
- let i = ce(t), a = [n?.trim() ? `Agent instructions:\n${n.trim()}` : "", r?.trim() ? `Knowledge context:\n${r.trim()}` : ""].filter(Boolean).join("\n\n");
43
+ `, fe = ({ selectedChatModel: e, requestHints: t, agentInstructions: n, knowledge: r }) => {
44
+ let i = U(t), a = [n?.trim() ? `Agent instructions:\n${n.trim()}` : "", r?.trim() ? `Knowledge context:\n${r.trim()}` : ""].filter(Boolean).join("\n\n");
45
45
  if (e.includes("reasoning") || e.includes("thinking")) {
46
- let t = e.startsWith("google/") && e.includes("thinking") ? `${W}\n\nWhen you reason, put your reasoning inside <thinking>...</thinking> tags. Then provide your final answer outside of those tags.\n\n${i}` : `${W}\n\n${i}`;
46
+ 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}`;
47
47
  return a ? `${t}\n\n${a}` : t;
48
48
  }
49
- let o = `${W}\n\n${i}\n\n${U}`;
49
+ let o = `${H}\n\n${i}\n\n${V}`;
50
50
  return a ? `${o}\n\n${a}` : o;
51
- }, ue = "\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", de = "\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", G = (e, t) => {
51
+ }, pe = "\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", me = "\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", W = (e, t) => {
52
52
  let n = "document";
53
53
  return t === "code" ? n = "script" : t === "sheet" && (n = "spreadsheet"), `Rewrite the following ${n} based on the given prompt.
54
54
 
55
55
  ${e}`;
56
- }, fe = "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", K = [
56
+ }, he = "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", ge = [
57
57
  "text",
58
58
  "code",
59
59
  "sheet"
60
- ], pe = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, q = () => !pe(process.env.AGENT_SDK_LIVE_TOOLS) && (pe(process.env.PLAYWRIGHT) || process.env.NODE_ENV === "test"), me = async ({ system: e, prompt: t, dataStream: n, providerOptions: r }) => {
61
- if (q()) {
60
+ ], _e = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, G = () => !_e(process.env.AGENT_SDK_LIVE_TOOLS) && (_e(process.env.PLAYWRIGHT) || process.env.NODE_ENV === "test"), ve = async ({ system: e, prompt: t, dataStream: n, providerOptions: r }) => {
61
+ if (G()) {
62
62
  let e = `Stub document: ${t}`;
63
63
  return n.write({
64
64
  type: "data-textDelta",
@@ -66,10 +66,10 @@ ${e}`;
66
66
  transient: !0
67
67
  }), e;
68
68
  }
69
- let i = "", { fullStream: a } = x({
70
- model: H(),
69
+ let i = "", { fullStream: a } = C({
70
+ model: B(),
71
71
  system: e,
72
- experimental_transform: y({ chunking: "word" }),
72
+ experimental_transform: ne({ chunking: "word" }),
73
73
  prompt: t,
74
74
  providerOptions: r
75
75
  });
@@ -79,8 +79,8 @@ ${e}`;
79
79
  transient: !0
80
80
  }));
81
81
  return i;
82
- }, he = async ({ system: e, prompt: t, dataStream: n }) => {
83
- if (q()) {
82
+ }, ye = async ({ system: e, prompt: t, dataStream: n }) => {
83
+ if (G()) {
84
84
  let e = `print("Stub code for: ${t}")\n`;
85
85
  return n.write({
86
86
  type: "data-codeDelta",
@@ -88,11 +88,11 @@ ${e}`;
88
88
  transient: !0
89
89
  }), e;
90
90
  }
91
- let r = "", { fullStream: i } = b({
92
- model: H(),
91
+ let r = "", { fullStream: i } = S({
92
+ model: B(),
93
93
  system: e,
94
94
  prompt: t,
95
- schema: j.object({ code: j.string() })
95
+ schema: M.object({ code: M.string() })
96
96
  });
97
97
  for await (let e of i) {
98
98
  if (e.type !== "object") continue;
@@ -104,8 +104,8 @@ ${e}`;
104
104
  }), r = t);
105
105
  }
106
106
  return r;
107
- }, ge = async ({ system: e, prompt: t, dataStream: n }) => {
108
- if (q()) {
107
+ }, be = async ({ system: e, prompt: t, dataStream: n }) => {
108
+ if (G()) {
109
109
  let e = `name,value\n${t.replaceAll(",", " ")},1\n`;
110
110
  return n.write({
111
111
  type: "data-sheetDelta",
@@ -113,11 +113,11 @@ ${e}`;
113
113
  transient: !0
114
114
  }), e;
115
115
  }
116
- let r = "", { fullStream: i } = b({
117
- model: H(),
116
+ let r = "", { fullStream: i } = S({
117
+ model: B(),
118
118
  system: e,
119
119
  prompt: t,
120
- schema: j.object({ csv: j.string().describe("CSV data") })
120
+ schema: M.object({ csv: M.string().describe("CSV data") })
121
121
  });
122
122
  for await (let e of i) {
123
123
  if (e.type !== "object") continue;
@@ -133,7 +133,7 @@ ${e}`;
133
133
  data: r,
134
134
  transient: !0
135
135
  }), r;
136
- }, _e = async (e) => {
136
+ }, xe = async (e) => {
137
137
  try {
138
138
  let t = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(e)}&count=1&language=en&format=json`);
139
139
  if (!t.ok) return null;
@@ -147,22 +147,22 @@ ${e}`;
147
147
  } catch {
148
148
  return null;
149
149
  }
150
- }, ve = ({ ctx: e, dataStream: t, requestHints: n }) => {
150
+ }, Se = ({ ctx: e, dataStream: t, requestHints: n }) => {
151
151
  let r = i(e), a = async (t) => {
152
- let n = await p(e, t);
152
+ let n = await m(e, t);
153
153
  return n.length > 0 ? n.at(-1) ?? null : null;
154
- }, o = S({
154
+ }, o = w({
155
155
  description: "Get the current weather at a location. You can provide either coordinates or a city name.",
156
- inputSchema: j.object({
157
- latitude: j.number().optional(),
158
- longitude: j.number().optional(),
159
- city: j.string().describe("City name (e.g., 'San Francisco', 'New York', 'London')").optional()
156
+ inputSchema: M.object({
157
+ latitude: M.number().optional(),
158
+ longitude: M.number().optional(),
159
+ city: M.string().describe("City name (e.g., 'San Francisco', 'New York', 'London')").optional()
160
160
  }),
161
161
  needsApproval: !0,
162
162
  execute: async (e) => {
163
163
  let t, n;
164
164
  if (e.city) {
165
- let r = await _e(e.city);
165
+ let r = await xe(e.city);
166
166
  if (!r) return { error: `Could not find coordinates for "${e.city}". Please check the city name.` };
167
167
  t = r.latitude, n = r.longitude;
168
168
  } else if (e.latitude !== void 0 && e.longitude !== void 0) t = e.latitude, n = e.longitude;
@@ -170,14 +170,14 @@ ${e}`;
170
170
  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();
171
171
  return "city" in e && (r.cityName = e.city), r;
172
172
  }
173
- }), c = S({
173
+ }), s = w({
174
174
  description: "Create an artifact for writing or content creation. Use kind 'code' for programming, 'text' for writing, and 'sheet' for spreadsheets or tabular data.",
175
- inputSchema: j.object({
176
- title: j.string().describe("The title of the artifact"),
177
- kind: j.enum(K).describe("Use 'code' for programming, 'text' for prose, and 'sheet' for CSV/tabular data")
175
+ inputSchema: M.object({
176
+ title: M.string().describe("The title of the artifact"),
177
+ kind: M.enum(ge).describe("Use 'code' for programming, 'text' for prose, and 'sheet' for CSV/tabular data")
178
178
  }),
179
179
  execute: async ({ title: n, kind: r }) => {
180
- let i = E();
180
+ let i = D();
181
181
  t.write({
182
182
  type: "data-kind",
183
183
  data: r,
@@ -196,19 +196,19 @@ ${e}`;
196
196
  transient: !0
197
197
  });
198
198
  let a = "";
199
- return r === "text" ? a = await me({
199
+ return r === "text" ? a = await ve({
200
200
  system: "Write about the given topic. Markdown is supported. Use headings wherever appropriate.",
201
201
  prompt: n,
202
202
  dataStream: t
203
- }) : r === "code" ? a = await he({
204
- system: ue,
203
+ }) : r === "code" ? a = await ye({
204
+ system: pe,
205
205
  prompt: n,
206
206
  dataStream: t
207
- }) : r === "sheet" && (a = await ge({
208
- system: de,
207
+ }) : r === "sheet" && (a = await be({
208
+ system: me,
209
209
  prompt: n,
210
210
  dataStream: t
211
- })), await u(e, {
211
+ })), await d(e, {
212
212
  id: i,
213
213
  title: n,
214
214
  kind: r,
@@ -224,40 +224,40 @@ ${e}`;
224
224
  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."
225
225
  };
226
226
  }
227
- }), l = S({
227
+ }), l = w({
228
228
  description: "Fully rewrite an existing artifact with the given description. Use editDocument instead for targeted find-and-replace changes.",
229
- inputSchema: j.object({
230
- id: j.string().describe("The ID of the artifact to rewrite"),
231
- description: j.string().default("Improve the content").describe("The description of changes that need to be made")
229
+ inputSchema: M.object({
230
+ id: M.string().describe("The ID of the artifact to rewrite"),
231
+ description: M.string().default("Improve the content").describe("The description of changes that need to be made")
232
232
  }),
233
233
  execute: async ({ id: n, description: r }) => {
234
234
  let i = await a(n);
235
235
  if (!i) return { error: "Document not found" };
236
236
  let o = i.kind;
237
- if (!K.includes(o)) return { error: `Unsupported document kind: ${i.kind}` };
237
+ if (!ge.includes(o)) return { error: `Unsupported document kind: ${i.kind}` };
238
238
  t.write({
239
239
  type: "data-clear",
240
240
  data: null,
241
241
  transient: !0
242
242
  });
243
243
  let s = "";
244
- return o === "text" ? s = await me({
245
- system: G(i.content, i.kind),
244
+ return o === "text" ? s = await ve({
245
+ system: W(i.content, i.kind),
246
246
  prompt: r,
247
247
  dataStream: t,
248
248
  providerOptions: { openai: { prediction: {
249
249
  type: "content",
250
250
  content: i.content
251
251
  } } }
252
- }) : o === "code" ? s = await he({
253
- system: G(i.content, i.kind),
252
+ }) : o === "code" ? s = await ye({
253
+ system: W(i.content, i.kind),
254
254
  prompt: r,
255
255
  dataStream: t
256
- }) : o === "sheet" && (s = await ge({
257
- system: G(i.content, i.kind),
256
+ }) : o === "sheet" && (s = await be({
257
+ system: W(i.content, i.kind),
258
258
  prompt: r,
259
259
  dataStream: t
260
- })), await u(e, {
260
+ })), await d(e, {
261
261
  id: i.id,
262
262
  title: i.title,
263
263
  kind: i.kind,
@@ -276,24 +276,24 @@ ${e}`;
276
276
  });
277
277
  return {
278
278
  getWeather: o,
279
- createDocument: c,
280
- editDocument: S({
279
+ createDocument: s,
280
+ editDocument: w({
281
281
  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.",
282
- inputSchema: j.object({
283
- id: j.string().describe("The ID of the artifact to edit"),
284
- old_string: j.string().min(1).describe("Exact string to find. Include enough surrounding context to make the match unique."),
285
- new_string: j.string().describe("Replacement string"),
286
- replace_all: j.boolean().optional().describe("Replace all occurrences instead of only the first one")
282
+ inputSchema: M.object({
283
+ id: M.string().describe("The ID of the artifact to edit"),
284
+ old_string: M.string().min(1).describe("Exact string to find. Include enough surrounding context to make the match unique."),
285
+ new_string: M.string().describe("Replacement string"),
286
+ replace_all: M.boolean().optional().describe("Replace all occurrences instead of only the first one")
287
287
  }),
288
288
  execute: async ({ id: n, old_string: r, new_string: i, replace_all: o }) => {
289
289
  let s = await a(n);
290
290
  if (!s) return { error: "Document not found" };
291
291
  if (!s.content) return { error: "Document has no content" };
292
292
  let c = s.kind;
293
- if (!K.includes(c)) return { error: `Unsupported document kind: ${s.kind}` };
293
+ if (!ge.includes(c)) return { error: `Unsupported document kind: ${s.kind}` };
294
294
  if (!s.content.includes(r)) return { error: "old_string not found in document" };
295
295
  let l = o ? s.content.replaceAll(r, i) : s.content.replace(r, i);
296
- return await u(e, {
296
+ return await d(e, {
297
297
  id: s.id,
298
298
  title: s.title,
299
299
  kind: s.kind,
@@ -327,18 +327,18 @@ ${e}`;
327
327
  }
328
328
  }),
329
329
  updateDocument: l,
330
- requestSuggestions: S({
330
+ requestSuggestions: w({
331
331
  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.",
332
- inputSchema: j.object({ documentId: j.string().describe("The UUID of an existing document artifact that was previously created with createDocument") }),
332
+ inputSchema: M.object({ documentId: M.string().describe("The UUID of an existing document artifact that was previously created with createDocument") }),
333
333
  execute: async ({ documentId: n }) => {
334
334
  let i = await a(n);
335
335
  if (!i?.content) return { error: "Document not found" };
336
- if (q()) {
336
+ if (G()) {
337
337
  let a = {
338
338
  originalText: "Stub original sentence.",
339
339
  suggestedText: "Stub suggested sentence.",
340
340
  description: "Stub suggestion",
341
- id: E(),
341
+ id: D(),
342
342
  documentId: n,
343
343
  documentCreatedAt: i.createdAt,
344
344
  isResolved: !1,
@@ -349,7 +349,7 @@ ${e}`;
349
349
  type: "data-suggestion",
350
350
  data: a,
351
351
  transient: !0
352
- }), await s(e, {
352
+ }), await c(e, {
353
353
  documentId: n,
354
354
  suggestions: [a]
355
355
  }), {
@@ -359,24 +359,24 @@ ${e}`;
359
359
  message: "Suggestions have been added to the document"
360
360
  };
361
361
  }
362
- let o = [], { partialOutputStream: c } = x({
363
- model: H(),
362
+ let o = [], { partialOutputStream: s } = C({
363
+ model: B(),
364
364
  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.",
365
365
  prompt: i.content,
366
- output: _.array({ element: j.object({
367
- originalSentence: j.string().describe("The original sentence"),
368
- suggestedSentence: j.string().describe("The suggested sentence"),
369
- description: j.string().describe("The description of the suggestion")
366
+ output: y.array({ element: M.object({
367
+ originalSentence: M.string().describe("The original sentence"),
368
+ suggestedSentence: M.string().describe("The suggested sentence"),
369
+ description: M.string().describe("The description of the suggestion")
370
370
  }) })
371
371
  }), l = 0;
372
- for await (let e of c) if (e) for (let a = l; a < e.length; a++) {
372
+ for await (let e of s) if (e) for (let a = l; a < e.length; a++) {
373
373
  let s = e[a];
374
374
  if (!s?.originalSentence || !s?.suggestedSentence || !s?.description) continue;
375
375
  let c = {
376
376
  originalText: s.originalSentence,
377
377
  suggestedText: s.suggestedSentence,
378
378
  description: s.description,
379
- id: E(),
379
+ id: D(),
380
380
  documentId: n,
381
381
  documentCreatedAt: i.createdAt,
382
382
  isResolved: !1,
@@ -389,7 +389,7 @@ ${e}`;
389
389
  transient: !0
390
390
  }), o.push(c), l++;
391
391
  }
392
- return o.length > 0 && await s(e, {
392
+ return o.length > 0 && await c(e, {
393
393
  documentId: n,
394
394
  suggestions: o
395
395
  }), {
@@ -410,34 +410,34 @@ ${e}`;
410
410
  }
411
411
  })
412
412
  };
413
- }, ye = (e) => e ? !e.trim() : !0, J = (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(), be = (e) => {
413
+ }, Ce = (e) => e ? !e.trim() : !0, K = (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(), we = (e) => {
414
414
  let t = e.trim();
415
415
  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;
416
- }, xe = (e) => {
416
+ }, Te = (e) => {
417
417
  let t = e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").replace(/\s+/g, " ").trim();
418
418
  return t === "hi" || t === "hello" || t === "hey" || t === "salut" || t === "bonjour";
419
- }, Y = (e) => {
419
+ }, q = (e) => {
420
420
  let t = e.trim();
421
- return !t || xe(t) ? "" : be(t.replaceAll("\n", " ").replaceAll("\r", " ").split(/\s+/).filter((e) => e.trim() !== "").slice(0, 5).join(" "));
422
- }, X = "/api/rb/agents/chat";
423
- j.any(), j.any();
424
- var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te = "test-model", Z = async (e) => new Promise((t) => setTimeout(t, e)), Q = async (e, t) => {
425
- let n = h(t);
426
- n && !n.isDone || await a(e, {
421
+ return !t || Te(t) ? "" : we(t.replaceAll("\n", " ").replaceAll("\r", " ").split(/\s+/).filter((e) => e.trim() !== "").slice(0, 5).join(" "));
422
+ }, J = "/api/rb/agents/chat";
423
+ M.any(), M.any();
424
+ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke = "test-model", Ae = "openai/gpt-5.4-mini", Y = async (e) => new Promise((t) => setTimeout(t, e)), X = async (e, t) => {
425
+ let n = _(t);
426
+ n && !n.isDone || await g(e, {
427
427
  chatId: t,
428
428
  isStreaming: !1
429
429
  });
430
- }, Ee = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, $ = (e) => typeof e == "string" && e.trim() || null, De = (e) => {
430
+ }, je = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, Z = (e) => typeof e == "string" && e.trim() || null, Me = (e) => {
431
431
  if (typeof e == "boolean") return e;
432
- let t = $(e)?.toLowerCase();
432
+ let t = Z(e)?.toLowerCase();
433
433
  return t ? t === "true" ? !0 : t === "false" ? !1 : null : null;
434
- }, Oe = (e) => {
434
+ }, Ne = (e) => {
435
435
  let t = e.req?.session?.user?.currentTenantId;
436
- return $(t);
437
- }, ke = (e) => {
436
+ return Z(t);
437
+ }, Pe = (e) => {
438
438
  let t = e.req?.session?.user?.id;
439
- return $(t);
440
- }, Ae = () => $(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", je = (e) => T("sha256").update(Buffer.from(e)).digest("hex"), Me = (e) => {
439
+ return Z(t);
440
+ }, Fe = () => Z(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", Ie = (e) => E("sha256").update(Buffer.from(e)).digest("hex"), Le = (e) => {
441
441
  let t = e.trim();
442
442
  if (!t) return null;
443
443
  let n;
@@ -450,36 +450,36 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
450
450
  return null;
451
451
  }
452
452
  }
453
- let r = we.exec(n.pathname);
453
+ let r = Oe.exec(n.pathname);
454
454
  if (!r) return null;
455
- let i = $(decodeURIComponent(r[1]));
455
+ let i = Z(decodeURIComponent(r[1]));
456
456
  return i ? {
457
457
  fileId: i,
458
- uploadKey: $(n.searchParams.get("rb-upload-key"))
458
+ uploadKey: Z(n.searchParams.get("rb-upload-key"))
459
459
  } : null;
460
- }, Ne = async ({ ctx: e, fileId: t, uploadKey: n }) => {
461
- let r = Oe(e);
460
+ }, Re = async ({ ctx: e, fileId: t, uploadKey: n }) => {
461
+ let r = Ne(e);
462
462
  if (!r) throw Error("tenant_missing");
463
463
  let i;
464
464
  try {
465
- i = new O(t);
465
+ i = new ae(t);
466
466
  } catch {
467
467
  throw Error("invalid_file_id");
468
468
  }
469
- let a = (await w(r)).db;
469
+ let a = (await T(r)).db;
470
470
  if (!a) throw Error("filesystem_db_unavailable");
471
- let o = new D(a, { bucketName: Ae() }), [s] = await o.find({ _id: i }).limit(1).toArray();
471
+ let o = new O(a, { bucketName: Fe() }), [s] = await o.find({ _id: i }).limit(1).toArray();
472
472
  if (!s) throw Error("file_not_found");
473
- let c = De(s?.metadata?.isPublic) ?? !1, l = ke(e), u = $(s?.metadata?.userId), d = $(s?.metadata?.ownerKeyHash);
473
+ let c = Me(s?.metadata?.isPublic) ?? !1, l = Pe(e), u = Z(s?.metadata?.userId), d = Z(s?.metadata?.ownerKeyHash);
474
474
  if (!c) {
475
- let e = !!(l && u && l === u), t = !!(n && d && je(n) === d);
475
+ let e = !!(l && u && l === u), t = !!(n && d && Ie(n) === d);
476
476
  if (!e && !t) throw Error("unauthorized");
477
477
  }
478
- let f = $(s?.metadata?.mimeType), p = [], m = 0;
478
+ let f = Z(s?.metadata?.mimeType), p = [], m = 0;
479
479
  return await new Promise((e, t) => {
480
480
  let n = o.openDownloadStream(i);
481
481
  n.on("data", (e) => {
482
- if (m += e.length, m > Se) {
482
+ if (m += e.length, m > Ee) {
483
483
  n.destroy(/* @__PURE__ */ Error("attachment_too_large"));
484
484
  return;
485
485
  }
@@ -489,16 +489,16 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
489
489
  data: Buffer.concat(p, m),
490
490
  mimeType: f
491
491
  };
492
- }, Pe = async (e, t) => {
492
+ }, ze = async (e, t) => {
493
493
  let n = Array.isArray(t) ? t : [], r = [];
494
494
  for (let t of n) {
495
495
  if (!t || typeof t != "object" || !("role" in t) || t.role !== "user") continue;
496
496
  let n = Array.isArray(t.content) ? t.content : null;
497
497
  if (n) for (let t of n) {
498
498
  if (!t || typeof t != "object" || t.type !== "file" || typeof t.data != "string") continue;
499
- let n = Me(t.data);
499
+ let n = Le(t.data);
500
500
  n && r.push((async () => {
501
- let { data: r, mimeType: i } = await Ne({
501
+ let { data: r, mimeType: i } = await Re({
502
502
  ctx: e,
503
503
  ...n
504
504
  });
@@ -507,7 +507,7 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
507
507
  }
508
508
  }
509
509
  r.length > 0 && await Promise.all(r);
510
- }, Fe = (e) => {
510
+ }, Be = (e) => {
511
511
  let t = Array.isArray(e) ? e : [];
512
512
  for (let e of t) {
513
513
  if (!e || typeof e != "object" || !("role" in e) || e.role !== "user") continue;
@@ -515,12 +515,12 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
515
515
  if (t) for (let e = 0; e < t.length; e += 1) {
516
516
  let n = t[e];
517
517
  if (!n || typeof n != "object" || n.type !== "file") continue;
518
- let r = $(n.mediaType);
518
+ let r = Z(n.mediaType);
519
519
  if (r?.startsWith("image/") || r === "application/pdf") continue;
520
- let i = $(n.filename) ?? $(n.name) ?? `attachment-${e + 1}`, a = n.data;
520
+ let i = Z(n.filename) ?? Z(n.name) ?? `attachment-${e + 1}`, a = n.data;
521
521
  if (r?.startsWith("text/") && a instanceof Uint8Array) {
522
522
  let n = (Buffer.isBuffer(a) ? a : Buffer.from(a)).toString("utf8");
523
- n.length > Ce && (n = `${n.slice(0, Ce)}\n\n[Truncated]`);
523
+ n.length > De && (n = `${n.slice(0, De)}\n\n[Truncated]`);
524
524
  let o = r === "text/csv" || i.toLowerCase().endsWith(".csv") ? "csv" : "";
525
525
  t[e] = {
526
526
  type: "text",
@@ -535,66 +535,66 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
535
535
  };
536
536
  }
537
537
  }
538
- }, Ie = async (e, t, n) => {
539
- if (e.message?.role === "user") return J(e.message.parts);
538
+ }, Ve = async (e, t, n) => {
539
+ if (e.message?.role === "user") return K(e.message.parts);
540
540
  if (Array.isArray(e.messages)) {
541
541
  let t = null;
542
542
  for (let n = e.messages.length - 1; n >= 0; --n) {
543
543
  let r = e.messages[n];
544
544
  if (r?.role !== "user") continue;
545
- let i = J(r.parts);
545
+ let i = K(r.parts);
546
546
  if (i) {
547
- if (Y(i)) return i;
547
+ if (q(i)) return i;
548
548
  t ??= i;
549
549
  }
550
550
  }
551
551
  if (t) return t;
552
552
  }
553
- let r = await l(t, n), i = null;
553
+ let r = await u(t, n), i = null;
554
554
  for (let e = r.length - 1; e >= 0; --e) {
555
555
  let t = r[e];
556
556
  if (t.role !== "user") continue;
557
- let n = J(t.parts);
557
+ let n = K(t.parts);
558
558
  if (n) {
559
- if (Y(n)) return n;
559
+ if (q(n)) return n;
560
560
  i ??= n;
561
561
  }
562
562
  }
563
563
  return i ?? "";
564
- }, Le = (e) => {
564
+ }, He = (e) => {
565
565
  let t = Array.isArray(e.messages) && e.messages.length > 0 ? e.messages.at(-1) : e.message;
566
566
  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();
567
- }, Re = (e) => {
567
+ }, Ue = (e) => {
568
568
  let t = e.id;
569
569
  return typeof t == "string" && t.trim() !== "" ? t : null;
570
- }, ze = (e) => {
570
+ }, We = (e) => {
571
571
  let t = e.selectedChatModel;
572
572
  return typeof t == "string" && t.trim() !== "" ? t : null;
573
- }, Be = (e) => {
573
+ }, Ge = (e) => {
574
574
  let t = e.openaiReasoningEffort;
575
575
  return typeof t == "string" && t.trim() !== "" ? t.trim() : null;
576
- }, Ve = (e) => {
576
+ }, Ke = (e) => {
577
577
  if (!e || typeof e != "object") return !1;
578
578
  let t = e.state, n = e.toolCallId;
579
579
  return typeof n == "string" && n.trim() !== "" && (t === "approval-responded" || t === "output-denied");
580
- }, He = (e) => {
580
+ }, qe = (e) => {
581
581
  let t = Array.isArray(e.messages) ? e.messages : [];
582
- return t.length === 0 || t.at(-1)?.role === "user" ? !1 : t.some((e) => (Array.isArray(e?.parts) ? e.parts : []).some((e) => Ve(e)));
583
- }, Ue = (e) => {
582
+ return t.length === 0 || t.at(-1)?.role === "user" ? !1 : t.some((e) => (Array.isArray(e?.parts) ? e.parts : []).some((e) => Ke(e)));
583
+ }, Je = (e) => {
584
584
  let t = /* @__PURE__ */ new Map();
585
585
  for (let n of e) {
586
586
  let e = Array.isArray(n?.parts) ? n.parts : [];
587
- for (let n of e) Ve(n) && t.set(n.toolCallId, n);
587
+ for (let n of e) Ke(n) && t.set(n.toolCallId, n);
588
588
  }
589
589
  return t;
590
- }, We = (e, t) => {
590
+ }, Ye = (e, t) => {
591
591
  let n = [];
592
592
  return {
593
593
  changedMessages: n,
594
594
  updatedMessages: e.map((e) => {
595
595
  let r = !1, i = e.parts.map((e) => {
596
596
  if (!e || typeof e != "object") return e;
597
- let n = $(e.toolCallId);
597
+ let n = Z(e.toolCallId);
598
598
  if (!n) return e;
599
599
  let i = t.get(n);
600
600
  return i ? (r = !0, {
@@ -610,23 +610,78 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
610
610
  return n.push(a), a;
611
611
  })
612
612
  };
613
- }, Ge = (e) => {
613
+ }, Xe = (e) => {
614
614
  if (!e || typeof e != "object" || !("createdAt" in e)) return null;
615
615
  let t = e.createdAt;
616
616
  if (typeof t != "string") return null;
617
617
  let n = new Date(t);
618
618
  return Number.isNaN(n.getTime()) ? null : n;
619
- }, Ke = (e) => ({
619
+ }, Ze = (e) => ({
620
620
  latitude: null,
621
621
  longitude: null,
622
622
  city: null,
623
623
  country: null
624
- }), qe = (e) => `agents-sdk:chat:${e}:stream`, Je = async ({ ctx: e, chatId: t, selectedChatModel: i }) => await r().resolveAgent?.({
624
+ }), Qe = (e) => {
625
+ let [t] = e.split("/");
626
+ return t && t !== e ? t : "unknown";
627
+ }, Q = (e) => typeof e == "number" && Number.isFinite(e) ? e : void 0, $e = (e) => e instanceof Error && e.message.trim() ? e.message : "Unknown error", et = (e) => {
628
+ 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 : {};
629
+ return {
630
+ inputTokens: Q(t.inputTokens),
631
+ outputTokens: Q(t.outputTokens),
632
+ totalTokens: Q(t.totalTokens),
633
+ cachedInputTokens: Q(n.cacheReadTokens) ?? Q(t.cachedInputTokens),
634
+ reasoningTokens: Q(r.reasoningTokens) ?? Q(t.reasoningTokens),
635
+ rawUsage: Object.keys(t).length > 0 ? t.raw ?? t : void 0
636
+ };
637
+ }, tt = () => ({
638
+ inputTokens: 0,
639
+ outputTokens: 0,
640
+ totalTokens: 0,
641
+ cachedInputTokens: 0,
642
+ reasoningTokens: 0
643
+ }), nt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a }) => {
644
+ try {
645
+ return { workspaceId: Z((await r().resolveUsageContext?.({
646
+ ctx: e,
647
+ chatId: t,
648
+ agent: n,
649
+ selectedChatModel: i,
650
+ mode: a
651
+ }))?.workspaceId) ?? void 0 };
652
+ } catch (e) {
653
+ return console.warn("Failed to resolve agent usage context.", e), { workspaceId: void 0 };
654
+ }
655
+ }, $ = async ({ ctx: e, usageContext: t, agent: n, chatId: r, mode: i, feature: o, modelId: s, status: c, billable: l, usage: u, finishReason: d, error: f, startedAt: p, finishedAt: m = /* @__PURE__ */ new Date() }) => {
656
+ let h = u ? et(u) : {}, g = {
657
+ id: D(),
658
+ workspaceId: t.workspaceId,
659
+ agentId: n.id,
660
+ chatId: r,
661
+ mode: i,
662
+ feature: o,
663
+ provider: Qe(s),
664
+ model: s,
665
+ billable: l,
666
+ status: c,
667
+ finishReason: Z(d) ?? void 0,
668
+ errorMessage: f ? $e(f) : void 0,
669
+ ...h,
670
+ startedAt: p,
671
+ finishedAt: m,
672
+ createdAt: /* @__PURE__ */ new Date()
673
+ };
674
+ try {
675
+ await a(e, g);
676
+ } catch (e) {
677
+ console.error("Failed to save agents usage event.", e);
678
+ }
679
+ }, rt = (e) => `agents-sdk:chat:${e}:stream`, it = async ({ ctx: e, chatId: t, selectedChatModel: i }) => await r().resolveAgent?.({
625
680
  ctx: e,
626
681
  chatId: t,
627
682
  selectedChatModel: i
628
- }) ?? n(), Ye = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
629
- let a = i(e), o = qe(t), s = g({
683
+ }) ?? n(), at = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
684
+ let a = i(e), o = rt(t), s = v({
630
685
  chatId: t,
631
686
  abortWhenNoSubscribersMs: n === "headless" || r ? 0 : void 0
632
687
  });
@@ -654,93 +709,104 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
654
709
  });
655
710
  }
656
711
  };
657
- }, Xe = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
712
+ }, ot = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
658
713
  if (!n) return;
659
714
  let a = i(e);
660
715
  n.publish({
661
716
  tenantId: a.tenantId,
662
717
  userId: a.userId,
663
- channel: qe(t),
718
+ channel: rt(t),
664
719
  payload: {
665
720
  chatId: t,
666
721
  message: r
667
722
  }
668
723
  });
669
- }, Ze = async ({ payload: n, ctx: s, mode: u = "interactive", streamTransport: d = null }) => {
670
- let p = Re(n);
671
- if (!p) return t(s, "bad_request:api", "Parameter id is required.");
672
- let h = n, g = ze(h), _ = Ee(process.env.PLAYWRIGHT), v = !Ee(process.env.AGENT_SDK_LIVE_CHAT) && _ || process.env.NODE_ENV === "test";
673
- if (!g) return t(s, "bad_request:api", "Parameter selectedChatModel is required.");
674
- if (g === Te && (v = !0), g !== Te && !ae.has(g)) return t(s, "bad_request:api", `Unsupported selectedChatModel: "${g}".`);
675
- let y = process.env.OPENAI_API_KEY, b = process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY, S = process.env.XAI_API_KEY, C = I(g), w = L(g), T = R(g), D = Be(h), O = D && D !== "default" && D !== "off" ? D : null, k = e(g);
676
- if (O && !k.some((e) => e === O)) return t(s, "bad_request:api", `Unsupported reasoning effort "${O}" for selectedChatModel: "${g}".`);
677
- if (!v && C && !y) return t(s, "bad_request:provider", "Missing OPENAI_API_KEY.");
678
- if (!v && w && !b) return t(s, "bad_request:provider", "Missing GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY).");
679
- if (!v && T && !S) return t(s, "bad_request:provider", "Missing XAI_API_KEY.");
680
- if (!v && !C && !w && !T) return t(s, "bad_request:provider", `Unsupported selectedChatModel: "${g}".`);
681
- let A = await Je({
682
- ctx: s,
683
- chatId: p,
684
- selectedChatModel: g
685
- }), ie = await r().resolveKnowledge?.({
686
- ctx: s,
687
- chatId: p,
688
- agent: A,
689
- selectedChatModel: g
690
- }) ?? null, j = i(s);
691
- await o(s, p) || await f(s, {
692
- id: p,
724
+ }, st = async ({ payload: n, ctx: a, mode: c = "interactive", streamTransport: d = null }) => {
725
+ let f = Ue(n);
726
+ if (!f) return t(a, "bad_request:api", "Parameter id is required.");
727
+ let m = n, _ = We(m), v = je(process.env.PLAYWRIGHT), y = !je(process.env.AGENT_SDK_LIVE_CHAT) && v || process.env.NODE_ENV === "test";
728
+ if (!_) return t(a, "bad_request:api", "Parameter selectedChatModel is required.");
729
+ if (_ === ke && (y = !0), _ !== ke && !oe.has(_)) return t(a, "bad_request:api", `Unsupported selectedChatModel: "${_}".`);
730
+ let x = process.env.OPENAI_API_KEY, ne = process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY, S = process.env.XAI_API_KEY, w = se(_), ie = ce(_), T = le(_), E = Ge(m), O = E && E !== "default" && E !== "off" ? E : null, ae = e(_);
731
+ if (O && !ae.some((e) => e === O)) return t(a, "bad_request:api", `Unsupported reasoning effort "${O}" for selectedChatModel: "${_}".`);
732
+ if (!y && w && !x) return t(a, "bad_request:provider", "Missing OPENAI_API_KEY.");
733
+ if (!y && ie && !ne) return t(a, "bad_request:provider", "Missing GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY).");
734
+ if (!y && T && !S) return t(a, "bad_request:provider", "Missing XAI_API_KEY.");
735
+ if (!y && !w && !ie && !T) return t(a, "bad_request:provider", `Unsupported selectedChatModel: "${_}".`);
736
+ let k = await it({
737
+ ctx: a,
738
+ chatId: f,
739
+ selectedChatModel: _
740
+ }), A = await r().resolveKnowledge?.({
741
+ ctx: a,
742
+ chatId: f,
743
+ agent: k,
744
+ selectedChatModel: _
745
+ }) ?? null, j = await nt({
746
+ ctx: a,
747
+ chatId: f,
748
+ agent: k,
749
+ selectedChatModel: _,
750
+ mode: c
751
+ }), M = i(a), N = await o(a, f, { includeDeleted: !0 });
752
+ if (N?.deletedAt) return t(a, "not_found:chat");
753
+ N ? N.selectedChatModel !== _ && await h(a, {
754
+ chatId: f,
755
+ selectedChatModel: _
756
+ }) : await p(a, {
757
+ id: f,
693
758
  createdAt: /* @__PURE__ */ new Date(),
694
- userId: j.userId,
759
+ userId: M.userId,
695
760
  title: "",
696
761
  isStreaming: !1,
762
+ selectedChatModel: _,
697
763
  lastContext: null
698
764
  });
699
- let M = h.message, N = typeof M?.id == "string" ? M.id : E(), P = Array.isArray(M?.parts) ? M?.parts : [];
700
- if ((typeof M?.role == "string" ? M.role : null) === "user") {
765
+ let P = m.message, F = typeof P?.id == "string" ? P.id : D(), I = Array.isArray(P?.parts) ? P?.parts : [];
766
+ if ((typeof P?.role == "string" ? P.role : null) === "user") {
701
767
  let e = /* @__PURE__ */ new Date();
702
- await c(s, [{
703
- id: N,
704
- chatId: p,
768
+ await l(a, [{
769
+ id: F,
770
+ chatId: f,
705
771
  role: "user",
706
- parts: P,
772
+ parts: I,
707
773
  attachments: [],
708
774
  createdAt: e
709
- }]), Xe({
710
- ctx: s,
711
- chatId: p,
775
+ }]), ot({
776
+ ctx: a,
777
+ chatId: f,
712
778
  streamTransport: d,
713
779
  message: {
714
- id: N,
780
+ id: F,
715
781
  role: "user",
716
- parts: P,
782
+ parts: I,
717
783
  metadata: { createdAt: e.toISOString() }
718
784
  }
719
785
  });
720
786
  }
721
- if (v) {
722
- await a(s, {
723
- chatId: p,
787
+ if (y) {
788
+ await g(a, {
789
+ chatId: f,
724
790
  isStreaming: !0
725
791
  });
726
- let e = Ye({
727
- ctx: s,
728
- chatId: p,
729
- mode: u,
792
+ let e = at({
793
+ ctx: a,
794
+ chatId: f,
795
+ mode: c,
730
796
  streamTransport: d
731
797
  });
732
798
  try {
733
- let t = Y(await Ie(h, s, p)), n = await o(s, p);
734
- n && ye(n.title) && t && t !== n.title && (await m(s, {
735
- chatId: p,
799
+ let t = q(await Ve(m, a, f)), n = await o(a, f);
800
+ n && Ce(n.title) && t && t !== n.title && (await s(a, {
801
+ chatId: f,
736
802
  title: t
737
803
  }), e.publishJson({
738
804
  type: "data-chat-title",
739
805
  data: t,
740
806
  transient: !0
741
807
  }));
742
- let r = E();
743
- _ && !e.abortController.signal.aborted && await Z(600), e.publishJson({
808
+ let r = D();
809
+ v && !e.abortController.signal.aborted && await Y(600), e.publishJson({
744
810
  type: "start",
745
811
  messageId: r
746
812
  });
@@ -749,18 +815,18 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
749
815
  type: "text-start",
750
816
  id: i
751
817
  });
752
- let a = Le(h), l = a ? `Echo: ${a}` : "Hello from agents-sdk", u = Date.now(), d = l.split(/(\s+)/).filter((e) => e.length > 0);
753
- for (let t of d) {
818
+ let u = He(m), d = u ? `Echo: ${u}` : "Hello from agents-sdk", p = Date.now(), h = d.split(/(\s+)/).filter((e) => e.length > 0);
819
+ for (let t of h) {
754
820
  if (e.abortController.signal.aborted) break;
755
821
  e.publishJson({
756
822
  type: "text-delta",
757
823
  id: i,
758
824
  delta: t
759
- }), await Z(_ ? 120 : 80);
825
+ }), await Y(v ? 120 : 80);
760
826
  }
761
- if (_ && !e.abortController.signal.aborted) {
762
- let e = Date.now() - u, t = 1200;
763
- e < t && await Z(t - e);
827
+ if (v && !e.abortController.signal.aborted) {
828
+ let e = Date.now() - p, t = 1200;
829
+ e < t && await Y(t - e);
764
830
  }
765
831
  return e.abortController.signal.aborted ? {} : (e.publishJson({
766
832
  type: "text-end",
@@ -768,118 +834,160 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
768
834
  }), e.publishJson({
769
835
  type: "finish",
770
836
  finishReason: "stop"
771
- }), e.publishDone(), await c(s, [{
837
+ }), e.publishDone(), await l(a, [{
772
838
  id: r,
773
- chatId: p,
839
+ chatId: f,
774
840
  role: "assistant",
775
841
  parts: [{
776
842
  type: "text",
777
- text: l
843
+ text: d
778
844
  }],
779
845
  attachments: [],
780
846
  createdAt: /* @__PURE__ */ new Date()
781
- }]), {});
847
+ }]), await $({
848
+ ctx: a,
849
+ usageContext: j,
850
+ agent: k,
851
+ chatId: f,
852
+ mode: c,
853
+ feature: "chat",
854
+ modelId: _,
855
+ status: "success",
856
+ billable: !1,
857
+ usage: tt(),
858
+ finishReason: "stop",
859
+ startedAt: new Date(p)
860
+ }), {});
782
861
  } finally {
783
- await Q(s, p);
862
+ await X(a, f);
784
863
  }
785
864
  }
786
- let F = Ke(s), B = He(h);
787
- if (Array.isArray(h.messages) && !B) {
788
- let e = h.messages.flatMap((e) => {
865
+ let R = Ze(a), z = qe(m);
866
+ if (Array.isArray(m.messages) && !z) {
867
+ let e = m.messages.flatMap((e) => {
789
868
  let t = typeof e?.id == "string" ? e.id : null, n = typeof e?.role == "string" ? e.role : null, r = Array.isArray(e?.parts) ? e.parts : [];
790
869
  return !t || !n ? [] : [{
791
870
  id: t,
792
- chatId: p,
871
+ chatId: f,
793
872
  role: n,
794
873
  parts: r,
795
874
  attachments: [],
796
- createdAt: Ge(e?.metadata) ?? /* @__PURE__ */ new Date()
875
+ createdAt: Xe(e?.metadata) ?? /* @__PURE__ */ new Date()
797
876
  }];
798
877
  });
799
- e.length > 0 && await c(s, e);
878
+ e.length > 0 && await l(a, e);
800
879
  }
801
- let V;
802
- if (Array.isArray(h.messages) && h.messages.length > 0 && B) {
803
- let e = await l(s, p);
804
- if (e.length === 0) V = h.messages;
880
+ let B;
881
+ if (Array.isArray(m.messages) && m.messages.length > 0 && z) {
882
+ let e = await u(a, f);
883
+ if (e.length === 0) B = m.messages;
805
884
  else {
806
- let { changedMessages: t, updatedMessages: n } = We(e, Ue(h.messages));
807
- t.length > 0 && await c(s, t), V = n.map((e) => ({
885
+ let { changedMessages: t, updatedMessages: n } = Ye(e, Je(m.messages));
886
+ t.length > 0 && await l(a, t), B = n.map((e) => ({
808
887
  id: e.id,
809
888
  role: e.role,
810
889
  parts: e.parts,
811
890
  metadata: { createdAt: e.createdAt.toISOString() }
812
891
  }));
813
892
  }
814
- } else V = Array.isArray(h.messages) && h.messages.length > 0 ? h.messages : (await l(s, p)).map((e) => ({
893
+ } else B = Array.isArray(m.messages) && m.messages.length > 0 ? m.messages : (await u(a, f)).map((e) => ({
815
894
  id: e.id,
816
895
  role: e.role,
817
896
  parts: e.parts,
818
897
  metadata: { createdAt: e.createdAt.toISOString() }
819
898
  }));
820
- await a(s, {
821
- chatId: p,
899
+ await g(a, {
900
+ chatId: f,
822
901
  isStreaming: !0
823
902
  });
824
- let H = Ye({
825
- ctx: s,
826
- chatId: p,
827
- mode: u,
903
+ let V = at({
904
+ ctx: a,
905
+ chatId: f,
906
+ mode: c,
828
907
  streamTransport: d
829
- }), U = "", W = "";
908
+ }), H = "", U = "";
830
909
  try {
831
- U = await Ie(h, s, p), W = Y(U);
832
- let e = await o(s, p);
833
- e && ye(e.title) && W && W !== e.title && (await m(s, {
834
- chatId: p,
835
- title: W
836
- }), H.publishJson({
910
+ H = await Ve(m, a, f), U = q(H);
911
+ let e = await o(a, f);
912
+ e && Ce(e.title) && U && U !== e.title && (await s(a, {
913
+ chatId: f,
914
+ title: U
915
+ }), V.publishJson({
837
916
  type: "data-chat-title",
838
- data: W,
917
+ data: U,
839
918
  transient: !0
840
919
  }));
841
920
  } catch (e) {
842
- console.error(e), H.publishJson({
921
+ console.error(e), V.publishJson({
843
922
  type: "error",
844
923
  errorText: "Something went wrong."
845
- }), H.publishDone();
924
+ }), V.publishDone();
846
925
  try {
847
- await Q(s, p);
926
+ await X(a, f);
848
927
  } catch (e) {
849
928
  console.error("Failed to update chat streaming state.", e);
850
929
  }
851
930
  return {};
852
931
  }
853
- U && W && y && (async () => {
932
+ H && U && x && (async () => {
933
+ let e = /* @__PURE__ */ new Date();
854
934
  try {
855
- let { text: e } = await ne({
856
- model: se(),
857
- system: fe,
858
- prompt: U
859
- }), t = be(e);
860
- if (!t) return;
861
- let n = await o(s, p);
935
+ let { text: t } = await te({
936
+ model: de(),
937
+ system: he,
938
+ prompt: H,
939
+ onFinish: async (t) => {
940
+ await $({
941
+ ctx: a,
942
+ usageContext: j,
943
+ agent: k,
944
+ chatId: f,
945
+ mode: c,
946
+ feature: "title",
947
+ modelId: Ae,
948
+ status: "success",
949
+ billable: !0,
950
+ usage: t.totalUsage ?? t.usage,
951
+ finishReason: t.finishReason,
952
+ startedAt: e
953
+ });
954
+ }
955
+ }), n = we(t);
862
956
  if (!n) return;
863
- n.title !== t && (await m(s, {
864
- chatId: p,
865
- title: t
866
- }), H.publishJson({
957
+ let r = await o(a, f);
958
+ if (!r) return;
959
+ r.title !== n && (await s(a, {
960
+ chatId: f,
961
+ title: n
962
+ }), V.publishJson({
867
963
  type: "data-chat-title",
868
- data: t,
964
+ data: n,
869
965
  transient: !0
870
966
  }));
871
- } catch (e) {
872
- console.warn("Failed to generate chat title.", e);
967
+ } catch (t) {
968
+ await $({
969
+ ctx: a,
970
+ usageContext: j,
971
+ agent: k,
972
+ chatId: f,
973
+ mode: c,
974
+ feature: "title",
975
+ modelId: Ae,
976
+ status: "error",
977
+ billable: !1,
978
+ error: t,
979
+ startedAt: e
980
+ }), console.warn("Failed to generate chat title.", t);
873
981
  }
874
982
  })();
875
- let ce = te({
876
- originalMessages: V,
983
+ let pe = b({
984
+ originalMessages: B,
877
985
  onError: (e) => (console.error(e), "Something went wrong."),
878
986
  onFinish: async ({ responseMessage: e }) => {
879
987
  let t = Array.isArray(e.parts) ? e.parts : [];
880
- await c(s, [{
881
- id: e.id ?? E(),
882
- chatId: p,
988
+ await l(a, [{
989
+ id: e.id ?? D(),
990
+ chatId: f,
883
991
  role: e.role ?? "assistant",
884
992
  parts: t,
885
993
  attachments: [],
@@ -887,10 +995,10 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
887
995
  }]);
888
996
  },
889
997
  execute: async ({ writer: e }) => {
890
- let t = ve({
891
- ctx: s,
998
+ let t = Se({
999
+ ctx: a,
892
1000
  dataStream: e,
893
- requestHints: F
1001
+ requestHints: R
894
1002
  }), n = [
895
1003
  "getWeather",
896
1004
  "createDocument",
@@ -904,87 +1012,123 @@ var Se = 1024 * 1024 * 20, Ce = 1e5, we = /^\/api\/rb\/files\/([^/]+)\/?$/, Te =
904
1012
  "editDocument",
905
1013
  "updateDocument",
906
1014
  "requestSuggestions"
907
- ], a = z(g), o = a ? [] : C ? n : i, c = t, l = o, u = await r().resolveTools?.({
908
- ctx: s,
1015
+ ], o = L(_), s = o ? [] : w ? n : i, l = t, u = s, d = await r().resolveTools?.({
1016
+ ctx: a,
909
1017
  dataStream: e,
910
- requestHints: F,
911
- agent: A,
912
- selectedChatModel: g,
1018
+ requestHints: R,
1019
+ agent: k,
1020
+ selectedChatModel: _,
913
1021
  availableTools: t,
914
- defaultActiveTools: o
1022
+ defaultActiveTools: s
915
1023
  });
916
- u && (c = u.tools, l = u.activeTools ?? Object.keys(u.tools));
917
- let d = await ee(V.map((e) => ({
1024
+ d && (l = d.tools, u = d.activeTools ?? Object.keys(d.tools));
1025
+ let p = await ee(B.map((e) => ({
918
1026
  role: e?.role,
919
1027
  parts: e?.parts,
920
1028
  metadata: e?.metadata
921
1029
  })), {
922
- tools: c,
1030
+ tools: l,
923
1031
  ignoreIncompleteToolCalls: !0
924
1032
  });
925
- await Pe(s, d), C && Fe(d);
926
- let f = typeof h.openaiReasoningSummary == "string" ? h.openaiReasoningSummary : null, p;
927
- C && O ? p = { openai: {
1033
+ await ze(a, p), w && Be(p);
1034
+ let h = typeof m.openaiReasoningSummary == "string" ? m.openaiReasoningSummary : null, g;
1035
+ w && O ? g = { openai: {
928
1036
  reasoningEffort: O,
929
- reasoningSummary: f ?? void 0
930
- } } : T && a && O && (p = { xai: { reasoningEffort: O } });
931
- let m = x({
932
- model: oe(g),
933
- system: le({
934
- selectedChatModel: g,
935
- requestHints: F,
936
- agentInstructions: A.instructions,
937
- knowledge: ie
1037
+ reasoningSummary: h ?? void 0
1038
+ } } : T && o && O && (g = { xai: { reasoningEffort: O } });
1039
+ let v = !1, y = /* @__PURE__ */ new Date(), b = async ({ status: e, usage: t, finishReason: n, error: r }) => {
1040
+ v || (v = !0, await $({
1041
+ ctx: a,
1042
+ usageContext: j,
1043
+ agent: k,
1044
+ chatId: f,
1045
+ mode: c,
1046
+ feature: "chat",
1047
+ modelId: _,
1048
+ status: e,
1049
+ billable: e === "success",
1050
+ usage: t,
1051
+ finishReason: n,
1052
+ error: r,
1053
+ startedAt: y
1054
+ }));
1055
+ }, x = C({
1056
+ model: ue(_),
1057
+ system: fe({
1058
+ selectedChatModel: _,
1059
+ requestHints: R,
1060
+ agentInstructions: k.instructions,
1061
+ knowledge: A
938
1062
  }),
939
- messages: d,
940
- tools: c,
1063
+ messages: p,
1064
+ tools: l,
941
1065
  stopWhen: re(5),
942
- abortSignal: H.abortController.signal,
943
- providerOptions: p,
944
- activeTools: l
1066
+ abortSignal: V.abortController.signal,
1067
+ providerOptions: g,
1068
+ activeTools: u,
1069
+ onFinish: async (e) => {
1070
+ await b({
1071
+ status: "success",
1072
+ usage: e.totalUsage ?? e.usage,
1073
+ finishReason: e.finishReason
1074
+ });
1075
+ },
1076
+ onError: async (e) => {
1077
+ await b({
1078
+ status: "error",
1079
+ error: e?.error ?? e
1080
+ });
1081
+ },
1082
+ onAbort: async (e) => {
1083
+ await b({
1084
+ status: "aborted",
1085
+ usage: e?.totalUsage ?? e?.usage,
1086
+ finishReason: e?.finishReason
1087
+ });
1088
+ }
945
1089
  });
946
- e.merge(m.toUIMessageStream({
947
- originalMessages: V,
948
- sendReasoning: a || !!(C && O)
1090
+ e.merge(x.toUIMessageStream({
1091
+ originalMessages: B,
1092
+ sendReasoning: o || !!(w && O)
949
1093
  }));
950
1094
  }
951
1095
  });
952
1096
  return (async () => {
953
1097
  let e = null;
954
1098
  try {
955
- let t = ce.getReader();
1099
+ let t = pe.getReader();
956
1100
  for (e = () => t.releaseLock();;) {
957
1101
  let { value: e, done: n } = await t.read();
958
1102
  if (n) break;
959
- H.publishJson(e);
1103
+ V.publishJson(e);
960
1104
  }
961
- H.publishDone();
1105
+ V.publishDone();
962
1106
  } catch (e) {
963
- console.error(e), H.publishJson({
1107
+ console.error(e), V.publishJson({
964
1108
  type: "error",
965
1109
  errorText: "Something went wrong."
966
- }), H.publishDone();
1110
+ }), V.publishDone();
967
1111
  } finally {
968
1112
  e?.();
969
1113
  try {
970
- await Q(s, p);
1114
+ await X(a, f);
971
1115
  } catch (e) {
972
1116
  console.error("Failed to update chat streaming state.", e);
973
1117
  }
974
1118
  }
975
1119
  })(), {};
976
- }, Qe = async (e, t) => Ze({
1120
+ }, ct = async (e, t) => st({
977
1121
  payload: e,
978
1122
  ctx: t,
979
1123
  mode: "interactive"
980
- }), $e = async (e, n) => {
1124
+ }), lt = async (e, n) => {
981
1125
  let r = n.req.query.id, i = Array.isArray(r) ? r[0] : r;
982
- return typeof i != "string" || i.trim() === "" ? t(n, "bad_request:api") : d(n, i);
983
- }, et = (e) => {
984
- e.get(X, (async (e, n) => {
1126
+ return typeof i != "string" || i.trim() === "" ? t(n, "bad_request:api") : f(n, i);
1127
+ }, ut = (e) => {
1128
+ e.get(J, (async (e, n) => {
985
1129
  let r = n.req.query.id, i = Array.isArray(r) ? r[0] : r;
986
1130
  return typeof i != "string" || i.trim() === "" ? t(n, "bad_request:api", "Parameter id is required.") : await o(n, i) || t(n, "not_found:chat");
987
- })), e.post(X, Qe), e.delete(X, $e);
1131
+ })), e.post(J, ct), e.delete(J, lt);
988
1132
  };
989
1133
  //#endregion
990
- export { et as default, Ze as runAgentLoop };
1134
+ export { ut as default, st as runAgentLoop };