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