@rpcbase/agents-sdk 0.6.0 → 0.8.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 (47) hide show
  1. package/dist/agents-sdk.css +1 -1
  2. package/dist/api/chat/handler.d.ts +3 -3
  3. package/dist/api/chat/handler.d.ts.map +1 -1
  4. package/dist/api/chat/historyCompaction.d.ts +29 -0
  5. package/dist/api/chat/historyCompaction.d.ts.map +1 -0
  6. package/dist/api/chat/models.d.ts +2 -2
  7. package/dist/api/chat/runtimeConfig.d.ts +39 -0
  8. package/dist/api/chat/runtimeConfig.d.ts.map +1 -1
  9. package/dist/api/chat/tools.d.ts +1835 -65
  10. package/dist/api/chat/tools.d.ts.map +1 -1
  11. package/dist/api/chatDb.d.ts +4 -0
  12. package/dist/api/chatDb.d.ts.map +1 -1
  13. package/dist/{chatDb-DdX0Vtyt.js → chatDb-BSiHIyn9.js} +25 -18
  14. package/dist/{chatDb-CcAjAGX7.js → chatDb-YfeABtn-.js} +25 -18
  15. package/dist/{chunk-BO2N2NFS-DQxiNvU-.js → chunk-BO2N2NFS-BDR8fnNb.js} +3967 -1844
  16. package/dist/client-routes.browser.js +1 -1
  17. package/dist/client-routes.js +1 -1
  18. package/dist/{data-stream-handler-Cs_bYM94.js → data-stream-handler-BW4eCG7d.js} +8513 -7111
  19. package/dist/{data-stream-handler-DdafwSP0.js → data-stream-handler-Bd_oM4r9.js} +8512 -7110
  20. package/dist/{handler-D7f8iAy5.js → handler-5n-YwiF3.js} +1 -1
  21. package/dist/{handler-CGV7uuUA.js → handler-B3uUDuTR.js} +1 -1
  22. package/dist/{handler-BLG0AYVC.js → handler-BMeUL2iE.js} +1 -1
  23. package/dist/{handler-C6u7vLAb.js → handler-BgYHL3BZ.js} +9 -9
  24. package/dist/{handler-dVlpopfq.js → handler-By86dyTJ.js} +1 -1
  25. package/dist/{handler-ClWOGjB_.js → handler-C06ydMqf.js} +422 -261
  26. package/dist/{handler-BeWk8pDD.js → handler-C0MO52d9.js} +1 -1
  27. package/dist/{handler-mbDBRYl8.js → handler-C8gaYgmy.js} +1 -1
  28. package/dist/{handler-B_ogBIj4.js → handler-DGbBgIt2.js} +347 -186
  29. package/dist/{handler-CEk1hut1.js → handler-DMwBT4bK.js} +1 -1
  30. package/dist/{handler-BY5bgBEh.js → handler-DdKB5P3H.js} +1 -1
  31. package/dist/{handler-BBCbPLLC.js → handler-Dy536I3-.js} +1 -1
  32. package/dist/{handler-BKT8Hl0a.js → handler-Jua6SU39.js} +9 -9
  33. package/dist/{handler-CZSMkZnQ.js → handler-YmuAR8ei.js} +1 -1
  34. package/dist/{handler-P40GjJry.js → handler-hah8tVEE.js} +1 -1
  35. package/dist/{handler-DbjPd3w4.js → handler-svaSKC2q.js} +1 -1
  36. package/dist/{highlighted-body-OFNGDK62-DRz4wOlV.js → highlighted-body-OFNGDK62-ChEBPTZ3.js} +1 -1
  37. package/dist/index.browser.js +1 -1
  38. package/dist/index.js +1 -1
  39. package/dist/mermaid-GHXKKRXX-fqlMH1Mi.js +2 -0
  40. package/dist/routes.browser.js +8 -8
  41. package/dist/routes.js +8 -8
  42. package/dist/runtime.d.ts +2 -2
  43. package/dist/runtime.d.ts.map +1 -1
  44. package/dist/runtime.js +1 -1
  45. package/dist/tailwind-source.js +1 -1
  46. package/package.json +22 -19
  47. package/dist/mermaid-GHXKKRXX-BE7_kWMj.js +0 -2
@@ -1,64 +1,203 @@
1
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, 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
- import { createGoogleGenerativeAI as k } from "@ai-sdk/google";
11
- import { openai as A } from "@ai-sdk/openai";
12
- import { createXai as j } from "@ai-sdk/xai";
13
- import { z as M } from "zod";
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, x as g, y as _ } from "./chatDb-YfeABtn-.js";
5
+ import { n as v, t as y } from "./resumableSse-BRFonw_y.js";
6
+ 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 oe, tool as S, wrapLanguageModel as se } from "ai";
7
+ import { getTenantFilesystemDb as C } from "@rpcbase/db";
8
+ import { createHash as w, randomUUID as T } from "node:crypto";
9
+ import { GridFSBucket as E, ObjectId as ce } from "mongodb";
10
+ import { createGoogleGenerativeAI as D } from "@ai-sdk/google";
11
+ import { openai as O } from "@ai-sdk/openai";
12
+ import { createXai as k } from "@ai-sdk/xai";
13
+ import { z as A } from "zod";
14
14
  //#region src/api/chat/models.ts
15
- var N = /-thinking$/, P = "openai/", F = "google/", I = "xai/", oe = new Set([
15
+ var j = /-thinking$/, M = "openai/", N = "google/", P = "xai/", le = 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
- ]), se = (e) => e.startsWith(P), ce = (e) => e.startsWith(F), le = (e) => e.startsWith(I), L = (e) => e.endsWith("-thinking"), R = j({
20
+ ]), ue = (e) => e.startsWith(M), de = (e) => e.startsWith(N), fe = (e) => e.startsWith(P), F = (e) => e.endsWith("-thinking"), I = k({
21
21
  baseURL: process.env.XAI_BASE_URL ?? "https://api.x.ai/v1",
22
22
  apiKey: process.env.XAI_API_KEY
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({
23
+ }), L = D({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY }), pe = (e) => {
24
+ if (ue(e)) return O.responses(e.slice(M.length));
25
+ if (de(e)) {
26
+ let t = e.slice(N.length).replace(j, ""), n = L.chat(t);
27
+ return F(e) ? se({
28
28
  model: n,
29
- middleware: x({ tagName: "thinking" })
29
+ middleware: ne({ tagName: "thinking" })
30
30
  }) : n;
31
31
  }
32
- if (le(e)) {
33
- let t = e.slice(I.length).replace(N, "");
34
- return L(e) ? R.responses(t) : R.chat(t);
32
+ if (fe(e)) {
33
+ let t = e.slice(P.length).replace(j, "");
34
+ return F(e) ? I.responses(t) : I.chat(t);
35
35
  }
36
36
  throw Error(`Unsupported modelId: ${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) => `\
37
+ }, me = () => O.chat("gpt-5.4-mini"), R = () => O.chat(process.env.AGENT_SDK_ARTIFACT_MODEL ?? "gpt-5.4-mini"), z = "\nArtifacts is a special user interface mode that helps users with writing, editing, and other content creation tasks. When artifact is open, it is on the right side of the screen, while the conversation is on the left side. When creating, editing, or updating documents, changes are reflected in real-time on the artifacts and visible to the user.\n\nWhen asked to write code, always use artifacts. When writing code, specify the language in the backticks, e.g. ```python`code here```. The default language is Python. Other languages are not yet supported, so let the user know if they request a different language.\n\nCritical rules:\n- Only call one artifact tool per response.\n- Do not update or edit a document immediately after creating it. Wait for user feedback or an explicit request to modify it.\n- After creating, editing, or updating an artifact, do not repeat the full artifact content in chat. The user can already see it.\n\nThis is a guide for using artifacts tools: `createDocument`, `editDocument`, `updateDocument`, and `requestSuggestions`, which render content on artifacts beside the conversation.\n\n**When to use `createDocument`:**\n- For substantial content (>10 lines) or code\n- For content users will likely save/reuse (emails, code, essays, etc.)\n- When explicitly requested to create a document\n- For when content contains a single code snippet\n- Use kind \"code\" for programming, \"text\" for writing, and \"sheet\" for tabular/CSV data\n\n**When NOT to use `createDocument`:**\n- For informational/explanatory content\n- For conversational responses\n- When asked to keep it in chat\n\n**Using `editDocument`:**\n- Prefer this for targeted edits to an existing artifact\n- For scripts: fixing bugs, adding/removing lines, renaming variables, adding logs\n- For documents: fixing typos, rewording paragraphs, inserting or replacing sections\n- Provide an exact `old_string` and `new_string`\n- Include enough surrounding context in `old_string` to make the match unique\n- Use `replace_all: true` only for deliberate repeated replacements, like renaming a variable everywhere\n\n**Using `updateDocument`:**\n- Default to full document rewrites for major changes\n- Use `editDocument` instead for specific, isolated changes\n- Follow user instructions for which parts to modify\n\n**When NOT to use `editDocument` or `updateDocument`:**\n- Immediately after creating a document\n- Without an explicit user request to modify the artifact\n\n**Using `requestSuggestions`:**\n- ONLY use when the user explicitly asks for suggestions on an existing document\n- Requires a valid document ID from a previously created document\n- Never use for general questions or information requests\n", B = "You are a friendly assistant! Keep your responses concise and helpful.\n\nWhen asked to write, create, or help with something, just do it directly. Don't ask clarifying questions unless absolutely necessary - make reasonable assumptions and proceed with the task.", V = (e) => `\
38
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
- `, 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");
43
+ `, he = ({ selectedChatModel: e, requestHints: t, agentInstructions: n, knowledge: r }) => {
44
+ let i = V(t), a = [n?.trim() ? `Agent instructions:\n${n.trim()}` : "", r?.trim() ? `Knowledge context:\n${r.trim()}` : ""].filter(Boolean).join("\n\n");
45
45
  if (e.includes("reasoning") || e.includes("thinking")) {
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}`;
46
+ 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
47
  return a ? `${t}\n\n${a}` : t;
48
48
  }
49
- let o = `${H}\n\n${i}\n\n${V}`;
49
+ let o = `${B}\n\n${i}\n\n${z}`;
50
50
  return a ? `${o}\n\n${a}` : o;
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) => {
51
+ }, H = "\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", U = "\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
- }, 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 = [
56
+ }, ge = "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", _e = 24, ve = 8e4, ye = 16e3, be = "agent-runtime-history-compaction-summary", G = (e) => !!e && typeof e == "object" && !Array.isArray(e), K = (e) => typeof e == "string" && e.trim() ? e.trim() : null, xe = (e) => {
57
+ let t = K((G(e.metadata) ? e.metadata : null)?.createdAt);
58
+ if (!t) return null;
59
+ let n = new Date(t);
60
+ return Number.isNaN(n.getTime()) ? null : t;
61
+ }, q = (e, t = 2e3) => {
62
+ if (typeof e == "string") return e.length > t ? `${e.slice(0, t)}...` : e;
63
+ if (typeof e == "number" || typeof e == "boolean") return String(e);
64
+ if (!e || typeof e != "object") return "";
65
+ try {
66
+ let n = JSON.stringify(e);
67
+ return n.length > t ? `${n.slice(0, t)}...` : n;
68
+ } catch {
69
+ return "[unserializable content]";
70
+ }
71
+ }, Se = (e) => (Array.isArray(e.parts) ? e.parts : []).flatMap((e) => {
72
+ if (!G(e)) {
73
+ let t = q(e);
74
+ return t ? [t] : [];
75
+ }
76
+ let t = K(e.type) ?? "part", n = q(e.text);
77
+ if (n) return [`${t}: ${n}`];
78
+ let r = q(e.output);
79
+ if (r) return [`${t}: ${r}`];
80
+ let i = q(e.result);
81
+ if (i) return [`${t}: ${i}`];
82
+ let a = q(e.content);
83
+ if (a) return [`${t}: ${a}`];
84
+ let o = q(e, 1e3);
85
+ return o ? [`${t}: ${o}`] : [];
86
+ }).join("\n").trim(), Ce = (e) => e.reduce((e, t) => e + Se(t).length, 0), we = (e, t) => {
87
+ if (e.length <= t) return e;
88
+ if (t <= 32) return e.slice(0, t);
89
+ let n = Math.floor(t * .7), r = Math.max(0, t - n - 24);
90
+ return `${e.slice(0, n)}\n...[compacted]...\n${e.slice(e.length - r)}`;
91
+ }, Te = (e) => e ? {
92
+ maxMessages: Number.isFinite(e.maxMessages) && Number(e.maxMessages) > 0 ? Math.floor(Number(e.maxMessages)) : _e,
93
+ maxEstimatedChars: Number.isFinite(e.maxEstimatedChars) && Number(e.maxEstimatedChars) > 0 ? Math.floor(Number(e.maxEstimatedChars)) : ve,
94
+ maxSummaryChars: Number.isFinite(e.maxSummaryChars) && Number(e.maxSummaryChars) > 0 ? Math.floor(Number(e.maxSummaryChars)) : ye
95
+ } : {
96
+ maxMessages: _e,
97
+ maxEstimatedChars: ve,
98
+ maxSummaryChars: ye
99
+ }, J = (e) => G(e) && e.type === "agent-runtime-history-compaction" && e.version === 1 && typeof e.summary == "string", Ee = (e) => J(e) ? e : G(e) && J(e.historyCompaction) ? e.historyCompaction : null, De = (e, t) => t ? G(e) && !J(e) ? {
100
+ ...e,
101
+ historyCompaction: t
102
+ } : { historyCompaction: t } : e ?? null, Oe = (e) => K(e.id), ke = (e, t) => {
103
+ let n = K(t?.compactedThroughMessageId);
104
+ return n ? e.findIndex((e) => Oe(e) === n) : -1;
105
+ }, Ae = (e, t) => {
106
+ let n = Math.max(1, t.maxMessages), r = Math.max(1, Math.min(e.length, Math.ceil(n / 3))), i = Math.max(0, e.length - n);
107
+ for (; i < e.length - r && Ce(e.slice(i)) > t.maxEstimatedChars;) i += 1;
108
+ return i;
109
+ }, je = (e) => {
110
+ let t = K(e.role) ?? "message", n = xe(e), r = Se(e);
111
+ return `${n ? `${t} (${n})` : t}:\n${r || "[non-text content]"}`;
112
+ }, Me = ({ previousContext: e, messagesToCompact: t, limits: n }) => {
113
+ let r = e?.summary?.trim(), i = t.map(je).join("\n\n").trim();
114
+ return we([r ? `Earlier summary:\n${r}` : null, i ? `Compacted transcript:\n${i}` : null].filter((e) => !!e).join("\n\n"), n.maxSummaryChars).trim();
115
+ }, Ne = (e) => ({
116
+ id: `${be}:${K(e.compactedThroughMessageId) ?? "unknown"}`,
117
+ role: "user",
118
+ parts: [{
119
+ type: "text",
120
+ text: [
121
+ "Context from earlier messages in this chat has been compacted for the model.",
122
+ "Use this summary as durable conversation memory, but prefer the recent messages when they conflict.",
123
+ "",
124
+ e.summary
125
+ ].join("\n")
126
+ }],
127
+ metadata: {
128
+ createdAt: e.compactedThroughMessageCreatedAt ?? e.updatedAt,
129
+ transient: !0,
130
+ historyCompaction: !0
131
+ }
132
+ }), Pe = (e, t) => t?.summary.trim() ? [Ne(t), ...e] : e, Fe = ({ messages: e, previousContext: t, limits: n }) => {
133
+ let r = ke(e, t), i = r >= 0 ? e.slice(r + 1) : e;
134
+ if (!(i.length > n.maxMessages || Ce(i) > n.maxEstimatedChars)) return {
135
+ messages: Pe(i, t),
136
+ context: t
137
+ };
138
+ let a = Ae(i, n);
139
+ if (a <= 0) return {
140
+ messages: Pe(i, t),
141
+ context: t
142
+ };
143
+ let o = i.slice(0, a), s = i.slice(a), c = o.at(-1) ?? null, l = {
144
+ type: "agent-runtime-history-compaction",
145
+ version: 1,
146
+ summary: Me({
147
+ previousContext: t,
148
+ messagesToCompact: o,
149
+ limits: n
150
+ }),
151
+ compactedThroughMessageId: c ? Oe(c) : t?.compactedThroughMessageId ?? null,
152
+ compactedThroughMessageCreatedAt: c ? xe(c) : t?.compactedThroughMessageCreatedAt ?? null,
153
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
154
+ messageCount: e.length
155
+ };
156
+ return {
157
+ messages: Pe(s, l),
158
+ context: l
159
+ };
160
+ }, Ie = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a, messages: o, lastContext: s }) => {
161
+ let c = r().historyCompaction;
162
+ if (c === !1 || c && c.enabled === !1) return {
163
+ messages: o,
164
+ lastContext: s ?? null,
165
+ lastContextChanged: !1
166
+ };
167
+ let l = Te(c), u = Ee(s);
168
+ try {
169
+ let r = typeof c == "object" && typeof c.compact == "function" ? await c.compact({
170
+ ctx: e,
171
+ chatId: t,
172
+ agent: n,
173
+ selectedChatModel: i,
174
+ mode: a,
175
+ messages: o,
176
+ previousContext: u,
177
+ limits: l
178
+ }) : Fe({
179
+ messages: o,
180
+ previousContext: u,
181
+ limits: l
182
+ }), d = Array.isArray(r.messages) ? r.messages : o, f = r.context === void 0 ? u : r.context;
183
+ return {
184
+ messages: d,
185
+ lastContext: De(s, f ?? null),
186
+ lastContextChanged: f !== u
187
+ };
188
+ } catch (e) {
189
+ return console.warn("Failed to compact agent chat history.", e), {
190
+ messages: o,
191
+ lastContext: s ?? null,
192
+ lastContextChanged: !1
193
+ };
194
+ }
195
+ }, Le = [
57
196
  "text",
58
197
  "code",
59
198
  "sheet"
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()) {
199
+ ], Re = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, Y = () => !Re(process.env.AGENT_SDK_LIVE_TOOLS) && (Re(process.env.PLAYWRIGHT) || process.env.NODE_ENV === "test"), ze = async ({ system: e, prompt: t, dataStream: n, providerOptions: r }) => {
200
+ if (Y()) {
62
201
  let e = `Stub document: ${t}`;
63
202
  return n.write({
64
203
  type: "data-textDelta",
@@ -66,10 +205,10 @@ ${e}`;
66
205
  transient: !0
67
206
  }), e;
68
207
  }
69
- let i = "", { fullStream: a } = C({
70
- model: B(),
208
+ let i = "", { fullStream: a } = oe({
209
+ model: R(),
71
210
  system: e,
72
- experimental_transform: ne({ chunking: "word" }),
211
+ experimental_transform: ie({ chunking: "word" }),
73
212
  prompt: t,
74
213
  providerOptions: r
75
214
  });
@@ -79,8 +218,8 @@ ${e}`;
79
218
  transient: !0
80
219
  }));
81
220
  return i;
82
- }, ye = async ({ system: e, prompt: t, dataStream: n }) => {
83
- if (G()) {
221
+ }, Be = async ({ system: e, prompt: t, dataStream: n }) => {
222
+ if (Y()) {
84
223
  let e = `print("Stub code for: ${t}")\n`;
85
224
  return n.write({
86
225
  type: "data-codeDelta",
@@ -88,11 +227,11 @@ ${e}`;
88
227
  transient: !0
89
228
  }), e;
90
229
  }
91
- let r = "", { fullStream: i } = S({
92
- model: B(),
230
+ let r = "", { fullStream: i } = x({
231
+ model: R(),
93
232
  system: e,
94
233
  prompt: t,
95
- schema: M.object({ code: M.string() })
234
+ schema: A.object({ code: A.string() })
96
235
  });
97
236
  for await (let e of i) {
98
237
  if (e.type !== "object") continue;
@@ -104,8 +243,8 @@ ${e}`;
104
243
  }), r = t);
105
244
  }
106
245
  return r;
107
- }, be = async ({ system: e, prompt: t, dataStream: n }) => {
108
- if (G()) {
246
+ }, Ve = async ({ system: e, prompt: t, dataStream: n }) => {
247
+ if (Y()) {
109
248
  let e = `name,value\n${t.replaceAll(",", " ")},1\n`;
110
249
  return n.write({
111
250
  type: "data-sheetDelta",
@@ -113,11 +252,11 @@ ${e}`;
113
252
  transient: !0
114
253
  }), e;
115
254
  }
116
- let r = "", { fullStream: i } = S({
117
- model: B(),
255
+ let r = "", { fullStream: i } = x({
256
+ model: R(),
118
257
  system: e,
119
258
  prompt: t,
120
- schema: M.object({ csv: M.string().describe("CSV data") })
259
+ schema: A.object({ csv: A.string().describe("CSV data") })
121
260
  });
122
261
  for await (let e of i) {
123
262
  if (e.type !== "object") continue;
@@ -133,7 +272,7 @@ ${e}`;
133
272
  data: r,
134
273
  transient: !0
135
274
  }), r;
136
- }, xe = async (e) => {
275
+ }, He = async (e) => {
137
276
  try {
138
277
  let t = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(e)}&count=1&language=en&format=json`);
139
278
  if (!t.ok) return null;
@@ -147,22 +286,22 @@ ${e}`;
147
286
  } catch {
148
287
  return null;
149
288
  }
150
- }, Se = ({ ctx: e, dataStream: t, requestHints: n }) => {
289
+ }, Ue = ({ ctx: e, dataStream: t, requestHints: n }) => {
151
290
  let r = i(e), a = async (t) => {
152
291
  let n = await m(e, t);
153
292
  return n.length > 0 ? n.at(-1) ?? null : null;
154
- }, o = w({
293
+ }, o = S({
155
294
  description: "Get the current weather at a location. You can provide either coordinates or a city name.",
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()
295
+ inputSchema: A.object({
296
+ latitude: A.number().optional(),
297
+ longitude: A.number().optional(),
298
+ city: A.string().describe("City name (e.g., 'San Francisco', 'New York', 'London')").optional()
160
299
  }),
161
300
  needsApproval: !0,
162
301
  execute: async (e) => {
163
302
  let t, n;
164
303
  if (e.city) {
165
- let r = await xe(e.city);
304
+ let r = await He(e.city);
166
305
  if (!r) return { error: `Could not find coordinates for "${e.city}". Please check the city name.` };
167
306
  t = r.latitude, n = r.longitude;
168
307
  } else if (e.latitude !== void 0 && e.longitude !== void 0) t = e.latitude, n = e.longitude;
@@ -170,14 +309,14 @@ ${e}`;
170
309
  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
310
  return "city" in e && (r.cityName = e.city), r;
172
311
  }
173
- }), s = w({
312
+ }), s = S({
174
313
  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: 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")
314
+ inputSchema: A.object({
315
+ title: A.string().describe("The title of the artifact"),
316
+ kind: A.enum(Le).describe("Use 'code' for programming, 'text' for prose, and 'sheet' for CSV/tabular data")
178
317
  }),
179
318
  execute: async ({ title: n, kind: r }) => {
180
- let i = D();
319
+ let i = T();
181
320
  t.write({
182
321
  type: "data-kind",
183
322
  data: r,
@@ -196,16 +335,16 @@ ${e}`;
196
335
  transient: !0
197
336
  });
198
337
  let a = "";
199
- return r === "text" ? a = await ve({
338
+ return r === "text" ? a = await ze({
200
339
  system: "Write about the given topic. Markdown is supported. Use headings wherever appropriate.",
201
340
  prompt: n,
202
341
  dataStream: t
203
- }) : r === "code" ? a = await ye({
204
- system: pe,
342
+ }) : r === "code" ? a = await Be({
343
+ system: H,
205
344
  prompt: n,
206
345
  dataStream: t
207
- }) : r === "sheet" && (a = await be({
208
- system: me,
346
+ }) : r === "sheet" && (a = await Ve({
347
+ system: U,
209
348
  prompt: n,
210
349
  dataStream: t
211
350
  })), await d(e, {
@@ -224,24 +363,24 @@ ${e}`;
224
363
  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
364
  };
226
365
  }
227
- }), l = w({
366
+ }), l = S({
228
367
  description: "Fully rewrite an existing artifact with the given description. Use editDocument instead for targeted find-and-replace changes.",
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")
368
+ inputSchema: A.object({
369
+ id: A.string().describe("The ID of the artifact to rewrite"),
370
+ description: A.string().default("Improve the content").describe("The description of changes that need to be made")
232
371
  }),
233
372
  execute: async ({ id: n, description: r }) => {
234
373
  let i = await a(n);
235
374
  if (!i) return { error: "Document not found" };
236
375
  let o = i.kind;
237
- if (!ge.includes(o)) return { error: `Unsupported document kind: ${i.kind}` };
376
+ if (!Le.includes(o)) return { error: `Unsupported document kind: ${i.kind}` };
238
377
  t.write({
239
378
  type: "data-clear",
240
379
  data: null,
241
380
  transient: !0
242
381
  });
243
382
  let s = "";
244
- return o === "text" ? s = await ve({
383
+ return o === "text" ? s = await ze({
245
384
  system: W(i.content, i.kind),
246
385
  prompt: r,
247
386
  dataStream: t,
@@ -249,11 +388,11 @@ ${e}`;
249
388
  type: "content",
250
389
  content: i.content
251
390
  } } }
252
- }) : o === "code" ? s = await ye({
391
+ }) : o === "code" ? s = await Be({
253
392
  system: W(i.content, i.kind),
254
393
  prompt: r,
255
394
  dataStream: t
256
- }) : o === "sheet" && (s = await be({
395
+ }) : o === "sheet" && (s = await Ve({
257
396
  system: W(i.content, i.kind),
258
397
  prompt: r,
259
398
  dataStream: t
@@ -277,20 +416,20 @@ ${e}`;
277
416
  return {
278
417
  getWeather: o,
279
418
  createDocument: s,
280
- editDocument: w({
419
+ editDocument: S({
281
420
  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: 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")
421
+ inputSchema: A.object({
422
+ id: A.string().describe("The ID of the artifact to edit"),
423
+ old_string: A.string().min(1).describe("Exact string to find. Include enough surrounding context to make the match unique."),
424
+ new_string: A.string().describe("Replacement string"),
425
+ replace_all: A.boolean().optional().describe("Replace all occurrences instead of only the first one")
287
426
  }),
288
427
  execute: async ({ id: n, old_string: r, new_string: i, replace_all: o }) => {
289
428
  let s = await a(n);
290
429
  if (!s) return { error: "Document not found" };
291
430
  if (!s.content) return { error: "Document has no content" };
292
431
  let c = s.kind;
293
- if (!ge.includes(c)) return { error: `Unsupported document kind: ${s.kind}` };
432
+ if (!Le.includes(c)) return { error: `Unsupported document kind: ${s.kind}` };
294
433
  if (!s.content.includes(r)) return { error: "old_string not found in document" };
295
434
  let l = o ? s.content.replaceAll(r, i) : s.content.replace(r, i);
296
435
  return await d(e, {
@@ -327,18 +466,18 @@ ${e}`;
327
466
  }
328
467
  }),
329
468
  updateDocument: l,
330
- requestSuggestions: w({
469
+ requestSuggestions: S({
331
470
  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: M.object({ documentId: M.string().describe("The UUID of an existing document artifact that was previously created with createDocument") }),
471
+ inputSchema: A.object({ documentId: A.string().describe("The UUID of an existing document artifact that was previously created with createDocument") }),
333
472
  execute: async ({ documentId: n }) => {
334
473
  let i = await a(n);
335
474
  if (!i?.content) return { error: "Document not found" };
336
- if (G()) {
475
+ if (Y()) {
337
476
  let a = {
338
477
  originalText: "Stub original sentence.",
339
478
  suggestedText: "Stub suggested sentence.",
340
479
  description: "Stub suggestion",
341
- id: D(),
480
+ id: T(),
342
481
  documentId: n,
343
482
  documentCreatedAt: i.createdAt,
344
483
  isResolved: !1,
@@ -359,14 +498,14 @@ ${e}`;
359
498
  message: "Suggestions have been added to the document"
360
499
  };
361
500
  }
362
- let o = [], { partialOutputStream: s } = C({
363
- model: B(),
501
+ let o = [], { partialOutputStream: s } = oe({
502
+ model: R(),
364
503
  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
504
  prompt: i.content,
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")
505
+ output: b.array({ element: A.object({
506
+ originalSentence: A.string().describe("The original sentence"),
507
+ suggestedSentence: A.string().describe("The suggested sentence"),
508
+ description: A.string().describe("The description of the suggestion")
370
509
  }) })
371
510
  }), l = 0;
372
511
  for await (let e of s) if (e) for (let a = l; a < e.length; a++) {
@@ -376,7 +515,7 @@ ${e}`;
376
515
  originalText: s.originalSentence,
377
516
  suggestedText: s.suggestedSentence,
378
517
  description: s.description,
379
- id: D(),
518
+ id: T(),
380
519
  documentId: n,
381
520
  documentCreatedAt: i.createdAt,
382
521
  isResolved: !1,
@@ -400,7 +539,7 @@ ${e}`;
400
539
  };
401
540
  }
402
541
  }),
403
- webSearch: A.tools.webSearch({
542
+ webSearch: O.tools.webSearch({
404
543
  externalWebAccess: !0,
405
544
  searchContextSize: "medium",
406
545
  userLocation: {
@@ -410,34 +549,34 @@ ${e}`;
410
549
  }
411
550
  })
412
551
  };
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) => {
552
+ }, We = (e) => e ? !e.trim() : !0, Ge = (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(), Ke = (e) => {
414
553
  let t = e.trim();
415
554
  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
- }, Te = (e) => {
555
+ }, qe = (e) => {
417
556
  let t = e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").replace(/\s+/g, " ").trim();
418
557
  return t === "hi" || t === "hello" || t === "hey" || t === "salut" || t === "bonjour";
419
- }, q = (e) => {
558
+ }, X = (e) => {
420
559
  let t = e.trim();
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, {
560
+ return !t || qe(t) ? "" : Ke(t.replaceAll("\n", " ").replaceAll("\r", " ").split(/\s+/).filter((e) => e.trim() !== "").slice(0, 5).join(" "));
561
+ }, Je = "/api/rb/agents/chat";
562
+ A.any(), A.any();
563
+ var Ye = 1024 * 1024 * 20, Xe = 1e5, Ze = /^\/api\/rb\/files\/([^/]+)\/?$/, Qe = "test-model", $e = "openai/gpt-5.4-mini", et = async (e) => new Promise((t) => setTimeout(t, e)), tt = async (e, t) => {
564
+ let n = v(t);
565
+ n && !n.isDone || await s(e, {
427
566
  chatId: t,
428
567
  isStreaming: !1
429
568
  });
430
- }, je = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, Z = (e) => typeof e == "string" && e.trim() || null, Me = (e) => {
569
+ }, nt = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, Z = (e) => typeof e == "string" && e.trim() || null, rt = (e) => {
431
570
  if (typeof e == "boolean") return e;
432
571
  let t = Z(e)?.toLowerCase();
433
572
  return t ? t === "true" ? !0 : t === "false" ? !1 : null : null;
434
- }, Ne = (e) => {
573
+ }, it = (e) => {
435
574
  let t = e.req?.session?.user?.currentTenantId;
436
575
  return Z(t);
437
- }, Pe = (e) => {
576
+ }, at = (e) => {
438
577
  let t = e.req?.session?.user?.id;
439
578
  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) => {
579
+ }, ot = () => Z(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", st = (e) => w("sha256").update(Buffer.from(e)).digest("hex"), ct = (e) => {
441
580
  let t = e.trim();
442
581
  if (!t) return null;
443
582
  let n;
@@ -450,36 +589,36 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
450
589
  return null;
451
590
  }
452
591
  }
453
- let r = Oe.exec(n.pathname);
592
+ let r = Ze.exec(n.pathname);
454
593
  if (!r) return null;
455
594
  let i = Z(decodeURIComponent(r[1]));
456
595
  return i ? {
457
596
  fileId: i,
458
597
  uploadKey: Z(n.searchParams.get("rb-upload-key"))
459
598
  } : null;
460
- }, Re = async ({ ctx: e, fileId: t, uploadKey: n }) => {
461
- let r = Ne(e);
599
+ }, lt = async ({ ctx: e, fileId: t, uploadKey: n }) => {
600
+ let r = it(e);
462
601
  if (!r) throw Error("tenant_missing");
463
602
  let i;
464
603
  try {
465
- i = new ae(t);
604
+ i = new ce(t);
466
605
  } catch {
467
606
  throw Error("invalid_file_id");
468
607
  }
469
- let a = (await T(r)).db;
608
+ let a = (await C(r)).db;
470
609
  if (!a) throw Error("filesystem_db_unavailable");
471
- let o = new O(a, { bucketName: Fe() }), [s] = await o.find({ _id: i }).limit(1).toArray();
610
+ let o = new E(a, { bucketName: ot() }), [s] = await o.find({ _id: i }).limit(1).toArray();
472
611
  if (!s) throw Error("file_not_found");
473
- let c = Me(s?.metadata?.isPublic) ?? !1, l = Pe(e), u = Z(s?.metadata?.userId), d = Z(s?.metadata?.ownerKeyHash);
612
+ let c = rt(s?.metadata?.isPublic) ?? !1, l = at(e), u = Z(s?.metadata?.userId), d = Z(s?.metadata?.ownerKeyHash);
474
613
  if (!c) {
475
- let e = !!(l && u && l === u), t = !!(n && d && Ie(n) === d);
614
+ let e = !!(l && u && l === u), t = !!(n && d && st(n) === d);
476
615
  if (!e && !t) throw Error("unauthorized");
477
616
  }
478
617
  let f = Z(s?.metadata?.mimeType), p = [], m = 0;
479
618
  return await new Promise((e, t) => {
480
619
  let n = o.openDownloadStream(i);
481
620
  n.on("data", (e) => {
482
- if (m += e.length, m > Ee) {
621
+ if (m += e.length, m > Ye) {
483
622
  n.destroy(/* @__PURE__ */ Error("attachment_too_large"));
484
623
  return;
485
624
  }
@@ -489,16 +628,16 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
489
628
  data: Buffer.concat(p, m),
490
629
  mimeType: f
491
630
  };
492
- }, ze = async (e, t) => {
631
+ }, ut = async (e, t) => {
493
632
  let n = Array.isArray(t) ? t : [], r = [];
494
633
  for (let t of n) {
495
634
  if (!t || typeof t != "object" || !("role" in t) || t.role !== "user") continue;
496
635
  let n = Array.isArray(t.content) ? t.content : null;
497
636
  if (n) for (let t of n) {
498
637
  if (!t || typeof t != "object" || t.type !== "file" || typeof t.data != "string") continue;
499
- let n = Le(t.data);
638
+ let n = ct(t.data);
500
639
  n && r.push((async () => {
501
- let { data: r, mimeType: i } = await Re({
640
+ let { data: r, mimeType: i } = await lt({
502
641
  ctx: e,
503
642
  ...n
504
643
  });
@@ -507,7 +646,7 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
507
646
  }
508
647
  }
509
648
  r.length > 0 && await Promise.all(r);
510
- }, Be = (e) => {
649
+ }, dt = (e) => {
511
650
  let t = Array.isArray(e) ? e : [];
512
651
  for (let e of t) {
513
652
  if (!e || typeof e != "object" || !("role" in e) || e.role !== "user") continue;
@@ -520,7 +659,7 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
520
659
  let i = Z(n.filename) ?? Z(n.name) ?? `attachment-${e + 1}`, a = n.data;
521
660
  if (r?.startsWith("text/") && a instanceof Uint8Array) {
522
661
  let n = (Buffer.isBuffer(a) ? a : Buffer.from(a)).toString("utf8");
523
- n.length > De && (n = `${n.slice(0, De)}\n\n[Truncated]`);
662
+ n.length > Xe && (n = `${n.slice(0, Xe)}\n\n[Truncated]`);
524
663
  let o = r === "text/csv" || i.toLowerCase().endsWith(".csv") ? "csv" : "";
525
664
  t[e] = {
526
665
  type: "text",
@@ -535,16 +674,16 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
535
674
  };
536
675
  }
537
676
  }
538
- }, Ve = async (e, t, n) => {
539
- if (e.message?.role === "user") return K(e.message.parts);
677
+ }, ft = async (e, t, n) => {
678
+ if (e.message?.role === "user") return Ge(e.message.parts);
540
679
  if (Array.isArray(e.messages)) {
541
680
  let t = null;
542
681
  for (let n = e.messages.length - 1; n >= 0; --n) {
543
682
  let r = e.messages[n];
544
683
  if (r?.role !== "user") continue;
545
- let i = K(r.parts);
684
+ let i = Ge(r.parts);
546
685
  if (i) {
547
- if (q(i)) return i;
686
+ if (X(i)) return i;
548
687
  t ??= i;
549
688
  }
550
689
  }
@@ -554,40 +693,40 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
554
693
  for (let e = r.length - 1; e >= 0; --e) {
555
694
  let t = r[e];
556
695
  if (t.role !== "user") continue;
557
- let n = K(t.parts);
696
+ let n = Ge(t.parts);
558
697
  if (n) {
559
- if (q(n)) return n;
698
+ if (X(n)) return n;
560
699
  i ??= n;
561
700
  }
562
701
  }
563
702
  return i ?? "";
564
- }, He = (e) => {
703
+ }, pt = (e) => {
565
704
  let t = Array.isArray(e.messages) && e.messages.length > 0 ? e.messages.at(-1) : e.message;
566
705
  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
- }, Ue = (e) => {
706
+ }, mt = (e) => {
568
707
  let t = e.id;
569
708
  return typeof t == "string" && t.trim() !== "" ? t : null;
570
- }, We = (e) => {
709
+ }, ht = (e) => {
571
710
  let t = e.selectedChatModel;
572
711
  return typeof t == "string" && t.trim() !== "" ? t : null;
573
- }, Ge = (e) => {
712
+ }, gt = (e) => {
574
713
  let t = e.openaiReasoningEffort;
575
714
  return typeof t == "string" && t.trim() !== "" ? t.trim() : null;
576
- }, Ke = (e) => {
715
+ }, _t = (e) => {
577
716
  if (!e || typeof e != "object") return !1;
578
717
  let t = e.state, n = e.toolCallId;
579
718
  return typeof n == "string" && n.trim() !== "" && (t === "approval-responded" || t === "output-denied");
580
- }, qe = (e) => {
719
+ }, vt = (e) => {
581
720
  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) => Ke(e)));
583
- }, Je = (e) => {
721
+ return t.length === 0 || t.at(-1)?.role === "user" ? !1 : t.some((e) => (Array.isArray(e?.parts) ? e.parts : []).some((e) => _t(e)));
722
+ }, yt = (e) => {
584
723
  let t = /* @__PURE__ */ new Map();
585
724
  for (let n of e) {
586
725
  let e = Array.isArray(n?.parts) ? n.parts : [];
587
- for (let n of e) Ke(n) && t.set(n.toolCallId, n);
726
+ for (let n of e) _t(n) && t.set(n.toolCallId, n);
588
727
  }
589
728
  return t;
590
- }, Ye = (e, t) => {
729
+ }, bt = (e, t) => {
591
730
  let n = [];
592
731
  return {
593
732
  changedMessages: n,
@@ -610,21 +749,21 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
610
749
  return n.push(a), a;
611
750
  })
612
751
  };
613
- }, Xe = (e) => {
752
+ }, xt = (e) => {
614
753
  if (!e || typeof e != "object" || !("createdAt" in e)) return null;
615
754
  let t = e.createdAt;
616
755
  if (typeof t != "string") return null;
617
756
  let n = new Date(t);
618
757
  return Number.isNaN(n.getTime()) ? null : n;
619
- }, Ze = (e) => ({
758
+ }, St = (e) => ({
620
759
  latitude: null,
621
760
  longitude: null,
622
761
  city: null,
623
762
  country: null
624
- }), Qe = (e) => {
763
+ }), Ct = (e) => {
625
764
  let [t] = e.split("/");
626
765
  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) => {
766
+ }, Q = (e) => typeof e == "number" && Number.isFinite(e) ? e : void 0, wt = (e) => e instanceof Error && e.message.trim() ? e.message : "Unknown error", Tt = (e) => {
628
767
  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
768
  return {
630
769
  inputTokens: Q(t.inputTokens),
@@ -634,13 +773,13 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
634
773
  reasoningTokens: Q(r.reasoningTokens) ?? Q(t.reasoningTokens),
635
774
  rawUsage: Object.keys(t).length > 0 ? t.raw ?? t : void 0
636
775
  };
637
- }, tt = () => ({
776
+ }, Et = () => ({
638
777
  inputTokens: 0,
639
778
  outputTokens: 0,
640
779
  totalTokens: 0,
641
780
  cachedInputTokens: 0,
642
781
  reasoningTokens: 0
643
- }), nt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a }) => {
782
+ }), Dt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a }) => {
644
783
  try {
645
784
  return { workspaceId: Z((await r().resolveUsageContext?.({
646
785
  ctx: e,
@@ -653,19 +792,19 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
653
792
  return console.warn("Failed to resolve agent usage context.", e), { workspaceId: void 0 };
654
793
  }
655
794
  }, $ = 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(),
795
+ let h = u ? Tt(u) : {}, g = {
796
+ id: T(),
658
797
  workspaceId: t.workspaceId,
659
798
  agentId: n.id,
660
799
  chatId: r,
661
800
  mode: i,
662
801
  feature: o,
663
- provider: Qe(s),
802
+ provider: Ct(s),
664
803
  model: s,
665
804
  billable: l,
666
805
  status: c,
667
806
  finishReason: Z(d) ?? void 0,
668
- errorMessage: f ? $e(f) : void 0,
807
+ errorMessage: f ? wt(f) : void 0,
669
808
  ...h,
670
809
  startedAt: p,
671
810
  finishedAt: m,
@@ -676,12 +815,12 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
676
815
  } catch (e) {
677
816
  console.error("Failed to save agents usage event.", e);
678
817
  }
679
- }, rt = (e) => `agents-sdk:chat:${e}:stream`, it = async ({ ctx: e, chatId: t, selectedChatModel: i }) => await r().resolveAgent?.({
818
+ }, Ot = (e) => `agents-sdk:chat:${e}:stream`, kt = async ({ ctx: e, chatId: t, selectedChatModel: i }) => await r().resolveAgent?.({
680
819
  ctx: e,
681
820
  chatId: t,
682
821
  selectedChatModel: i
683
- }) ?? n(), at = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
684
- let a = i(e), o = rt(t), s = v({
822
+ }) ?? n(), At = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
823
+ let a = i(e), o = Ot(t), s = y({
685
824
  chatId: t,
686
825
  abortWhenNoSubscribersMs: n === "headless" || r ? 0 : void 0
687
826
  });
@@ -709,95 +848,95 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
709
848
  });
710
849
  }
711
850
  };
712
- }, ot = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
851
+ }, jt = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
713
852
  if (!n) return;
714
853
  let a = i(e);
715
854
  n.publish({
716
855
  tenantId: a.tenantId,
717
856
  userId: a.userId,
718
- channel: rt(t),
857
+ channel: Ot(t),
719
858
  payload: {
720
859
  chatId: t,
721
860
  message: r
722
861
  }
723
862
  });
724
- }, st = async ({ payload: n, ctx: a, mode: c = "interactive", streamTransport: d = null }) => {
725
- let f = Ue(n);
863
+ }, Mt = async ({ payload: n, ctx: a, mode: c = "interactive", streamTransport: d = null }) => {
864
+ let f = mt(n);
726
865
  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({
866
+ let m = n, v = ht(m), y = nt(process.env.PLAYWRIGHT), b = !nt(process.env.AGENT_SDK_LIVE_CHAT) && y || process.env.NODE_ENV === "test";
867
+ if (!v) return t(a, "bad_request:api", "Parameter selectedChatModel is required.");
868
+ if (v === Qe && (b = !0), v !== Qe && !le.has(v)) return t(a, "bad_request:api", `Unsupported selectedChatModel: "${v}".`);
869
+ let ne = process.env.OPENAI_API_KEY, ie = process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY, x = process.env.XAI_API_KEY, S = ue(v), se = de(v), C = fe(v), w = gt(m), E = w && w !== "default" && w !== "off" ? w : null, ce = e(v);
870
+ if (E && !ce.some((e) => e === E)) return t(a, "bad_request:api", `Unsupported reasoning effort "${E}" for selectedChatModel: "${v}".`);
871
+ if (!b && S && !ne) return t(a, "bad_request:provider", "Missing OPENAI_API_KEY.");
872
+ if (!b && se && !ie) return t(a, "bad_request:provider", "Missing GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY).");
873
+ if (!b && C && !x) return t(a, "bad_request:provider", "Missing XAI_API_KEY.");
874
+ if (!b && !S && !se && !C) return t(a, "bad_request:provider", `Unsupported selectedChatModel: "${v}".`);
875
+ let D = await kt({
737
876
  ctx: a,
738
877
  chatId: f,
739
- selectedChatModel: _
740
- }), A = await r().resolveKnowledge?.({
878
+ selectedChatModel: v
879
+ }), O = await r().resolveKnowledge?.({
741
880
  ctx: a,
742
881
  chatId: f,
743
- agent: k,
744
- selectedChatModel: _
745
- }) ?? null, j = await nt({
882
+ agent: D,
883
+ selectedChatModel: v
884
+ }) ?? null, k = await Dt({
746
885
  ctx: a,
747
886
  chatId: f,
748
- agent: k,
749
- selectedChatModel: _,
887
+ agent: D,
888
+ selectedChatModel: v,
750
889
  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, {
890
+ }), A = i(a), j = await o(a, f, { includeDeleted: !0 });
891
+ if (j?.deletedAt) return t(a, "not_found:chat");
892
+ j ? j.selectedChatModel !== v && await _(a, {
754
893
  chatId: f,
755
- selectedChatModel: _
894
+ selectedChatModel: v
756
895
  }) : await p(a, {
757
896
  id: f,
758
897
  createdAt: /* @__PURE__ */ new Date(),
759
- userId: M.userId,
898
+ userId: A.userId,
760
899
  title: "",
761
900
  isStreaming: !1,
762
- selectedChatModel: _,
901
+ selectedChatModel: v,
763
902
  lastContext: null
764
903
  });
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") {
904
+ let M = m.message, N = typeof M?.id == "string" ? M.id : T(), P = Array.isArray(M?.parts) ? M?.parts : [];
905
+ if ((typeof M?.role == "string" ? M.role : null) === "user") {
767
906
  let e = /* @__PURE__ */ new Date();
768
907
  await l(a, [{
769
- id: F,
908
+ id: N,
770
909
  chatId: f,
771
910
  role: "user",
772
- parts: I,
911
+ parts: P,
773
912
  attachments: [],
774
913
  createdAt: e
775
- }]), ot({
914
+ }]), jt({
776
915
  ctx: a,
777
916
  chatId: f,
778
917
  streamTransport: d,
779
918
  message: {
780
- id: F,
919
+ id: N,
781
920
  role: "user",
782
- parts: I,
921
+ parts: P,
783
922
  metadata: { createdAt: e.toISOString() }
784
923
  }
785
924
  });
786
925
  }
787
- if (y) {
788
- await g(a, {
926
+ if (b) {
927
+ await s(a, {
789
928
  chatId: f,
790
929
  isStreaming: !0
791
930
  });
792
- let e = at({
931
+ let e = At({
793
932
  ctx: a,
794
933
  chatId: f,
795
934
  mode: c,
796
935
  streamTransport: d
797
936
  });
798
937
  try {
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, {
938
+ let t = X(await ft(m, a, f)), n = await o(a, f);
939
+ n && We(n.title) && t && t !== n.title && (await g(a, {
801
940
  chatId: f,
802
941
  title: t
803
942
  }), e.publishJson({
@@ -805,8 +944,8 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
805
944
  data: t,
806
945
  transient: !0
807
946
  }));
808
- let r = D();
809
- v && !e.abortController.signal.aborted && await Y(600), e.publishJson({
947
+ let r = T();
948
+ y && !e.abortController.signal.aborted && await et(600), e.publishJson({
810
949
  type: "start",
811
950
  messageId: r
812
951
  });
@@ -815,18 +954,18 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
815
954
  type: "text-start",
816
955
  id: i
817
956
  });
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) {
957
+ let s = pt(m), u = s ? `Echo: ${s}` : "Hello from agents-sdk", d = Date.now(), p = u.split(/(\s+)/).filter((e) => e.length > 0);
958
+ for (let t of p) {
820
959
  if (e.abortController.signal.aborted) break;
821
960
  e.publishJson({
822
961
  type: "text-delta",
823
962
  id: i,
824
963
  delta: t
825
- }), await Y(v ? 120 : 80);
964
+ }), await et(y ? 120 : 80);
826
965
  }
827
- if (v && !e.abortController.signal.aborted) {
828
- let e = Date.now() - p, t = 1200;
829
- e < t && await Y(t - e);
966
+ if (y && !e.abortController.signal.aborted) {
967
+ let e = Date.now() - d, t = 1200;
968
+ e < t && await et(t - e);
830
969
  }
831
970
  return e.abortController.signal.aborted ? {} : (e.publishJson({
832
971
  type: "text-end",
@@ -840,30 +979,30 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
840
979
  role: "assistant",
841
980
  parts: [{
842
981
  type: "text",
843
- text: d
982
+ text: u
844
983
  }],
845
984
  attachments: [],
846
985
  createdAt: /* @__PURE__ */ new Date()
847
986
  }]), await $({
848
987
  ctx: a,
849
- usageContext: j,
850
- agent: k,
988
+ usageContext: k,
989
+ agent: D,
851
990
  chatId: f,
852
991
  mode: c,
853
992
  feature: "chat",
854
- modelId: _,
993
+ modelId: v,
855
994
  status: "success",
856
995
  billable: !1,
857
- usage: tt(),
996
+ usage: Et(),
858
997
  finishReason: "stop",
859
- startedAt: new Date(p)
998
+ startedAt: new Date(d)
860
999
  }), {});
861
1000
  } finally {
862
- await X(a, f);
1001
+ await tt(a, f);
863
1002
  }
864
1003
  }
865
- let R = Ze(a), z = qe(m);
866
- if (Array.isArray(m.messages) && !z) {
1004
+ let I = St(a), L = vt(m);
1005
+ if (Array.isArray(m.messages) && !L) {
867
1006
  let e = m.messages.flatMap((e) => {
868
1007
  let t = typeof e?.id == "string" ? e.id : null, n = typeof e?.role == "string" ? e.role : null, r = Array.isArray(e?.parts) ? e.parts : [];
869
1008
  return !t || !n ? [] : [{
@@ -872,44 +1011,66 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
872
1011
  role: n,
873
1012
  parts: r,
874
1013
  attachments: [],
875
- createdAt: Xe(e?.metadata) ?? /* @__PURE__ */ new Date()
1014
+ createdAt: xt(e?.metadata) ?? /* @__PURE__ */ new Date()
876
1015
  }];
877
1016
  });
878
1017
  e.length > 0 && await l(a, e);
879
1018
  }
880
- let B;
881
- if (Array.isArray(m.messages) && m.messages.length > 0 && z) {
1019
+ let R;
1020
+ if (Array.isArray(m.messages) && m.messages.length > 0 && L) {
882
1021
  let e = await u(a, f);
883
- if (e.length === 0) B = m.messages;
1022
+ if (e.length === 0) R = m.messages;
884
1023
  else {
885
- let { changedMessages: t, updatedMessages: n } = Ye(e, Je(m.messages));
886
- t.length > 0 && await l(a, t), B = n.map((e) => ({
1024
+ let { changedMessages: t, updatedMessages: n } = bt(e, yt(m.messages));
1025
+ t.length > 0 && await l(a, t), R = n.map((e) => ({
887
1026
  id: e.id,
888
1027
  role: e.role,
889
1028
  parts: e.parts,
890
1029
  metadata: { createdAt: e.createdAt.toISOString() }
891
1030
  }));
892
1031
  }
893
- } else B = Array.isArray(m.messages) && m.messages.length > 0 ? m.messages : (await u(a, f)).map((e) => ({
1032
+ } else R = Array.isArray(m.messages) && m.messages.length > 0 ? m.messages : (await u(a, f)).map((e) => ({
894
1033
  id: e.id,
895
1034
  role: e.role,
896
1035
  parts: e.parts,
897
1036
  metadata: { createdAt: e.createdAt.toISOString() }
898
1037
  }));
899
- await g(a, {
1038
+ let z = L ? {
1039
+ messages: R,
1040
+ lastContext: j?.lastContext ?? null,
1041
+ lastContextChanged: !1
1042
+ } : await Ie({
1043
+ ctx: a,
1044
+ chatId: f,
1045
+ agent: D,
1046
+ selectedChatModel: v,
1047
+ mode: c,
1048
+ messages: R,
1049
+ lastContext: j?.lastContext ?? null
1050
+ });
1051
+ if (!L && z.lastContextChanged) try {
1052
+ await h(a, {
1053
+ chatId: f,
1054
+ lastContext: z.lastContext
1055
+ });
1056
+ } catch (e) {
1057
+ console.warn("Failed to save compacted agent chat history context.", e);
1058
+ }
1059
+ let B = z.messages;
1060
+ await s(a, {
900
1061
  chatId: f,
901
1062
  isStreaming: !0
902
1063
  });
903
- let V = at({
1064
+ let V = At({
904
1065
  ctx: a,
905
1066
  chatId: f,
906
1067
  mode: c,
907
1068
  streamTransport: d
908
1069
  }), H = "", U = "";
909
1070
  try {
910
- H = await Ve(m, a, f), U = q(H);
1071
+ H = await ft(m, a, f), U = X(H);
911
1072
  let e = await o(a, f);
912
- e && Ce(e.title) && U && U !== e.title && (await s(a, {
1073
+ e && We(e.title) && U && U !== e.title && (await g(a, {
913
1074
  chatId: f,
914
1075
  title: U
915
1076
  }), V.publishJson({
@@ -923,28 +1084,28 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
923
1084
  errorText: "Something went wrong."
924
1085
  }), V.publishDone();
925
1086
  try {
926
- await X(a, f);
1087
+ await tt(a, f);
927
1088
  } catch (e) {
928
1089
  console.error("Failed to update chat streaming state.", e);
929
1090
  }
930
1091
  return {};
931
1092
  }
932
- H && U && x && (async () => {
1093
+ H && U && ne && (async () => {
933
1094
  let e = /* @__PURE__ */ new Date();
934
1095
  try {
935
- let { text: t } = await te({
936
- model: de(),
937
- system: he,
1096
+ let { text: t } = await re({
1097
+ model: me(),
1098
+ system: ge,
938
1099
  prompt: H,
939
1100
  onFinish: async (t) => {
940
1101
  await $({
941
1102
  ctx: a,
942
- usageContext: j,
943
- agent: k,
1103
+ usageContext: k,
1104
+ agent: D,
944
1105
  chatId: f,
945
1106
  mode: c,
946
1107
  feature: "title",
947
- modelId: Ae,
1108
+ modelId: $e,
948
1109
  status: "success",
949
1110
  billable: !0,
950
1111
  usage: t.totalUsage ?? t.usage,
@@ -952,11 +1113,11 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
952
1113
  startedAt: e
953
1114
  });
954
1115
  }
955
- }), n = we(t);
1116
+ }), n = Ke(t);
956
1117
  if (!n) return;
957
1118
  let r = await o(a, f);
958
1119
  if (!r) return;
959
- r.title !== n && (await s(a, {
1120
+ r.title !== n && (await g(a, {
960
1121
  chatId: f,
961
1122
  title: n
962
1123
  }), V.publishJson({
@@ -967,12 +1128,12 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
967
1128
  } catch (t) {
968
1129
  await $({
969
1130
  ctx: a,
970
- usageContext: j,
971
- agent: k,
1131
+ usageContext: k,
1132
+ agent: D,
972
1133
  chatId: f,
973
1134
  mode: c,
974
1135
  feature: "title",
975
- modelId: Ae,
1136
+ modelId: $e,
976
1137
  status: "error",
977
1138
  billable: !1,
978
1139
  error: t,
@@ -980,13 +1141,13 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
980
1141
  }), console.warn("Failed to generate chat title.", t);
981
1142
  }
982
1143
  })();
983
- let pe = b({
984
- originalMessages: B,
1144
+ let W = te({
1145
+ originalMessages: R,
985
1146
  onError: (e) => (console.error(e), "Something went wrong."),
986
1147
  onFinish: async ({ responseMessage: e }) => {
987
1148
  let t = Array.isArray(e.parts) ? e.parts : [];
988
1149
  await l(a, [{
989
- id: e.id ?? D(),
1150
+ id: e.id ?? T(),
990
1151
  chatId: f,
991
1152
  role: e.role ?? "assistant",
992
1153
  parts: t,
@@ -995,10 +1156,10 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
995
1156
  }]);
996
1157
  },
997
1158
  execute: async ({ writer: e }) => {
998
- let t = Se({
1159
+ let t = Ue({
999
1160
  ctx: a,
1000
1161
  dataStream: e,
1001
- requestHints: R
1162
+ requestHints: I
1002
1163
  }), n = [
1003
1164
  "getWeather",
1004
1165
  "createDocument",
@@ -1012,12 +1173,12 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
1012
1173
  "editDocument",
1013
1174
  "updateDocument",
1014
1175
  "requestSuggestions"
1015
- ], o = L(_), s = o ? [] : w ? n : i, l = t, u = s, d = await r().resolveTools?.({
1176
+ ], o = F(v), s = o ? [] : S ? n : i, l = t, u = s, d = await r().resolveTools?.({
1016
1177
  ctx: a,
1017
1178
  dataStream: e,
1018
- requestHints: R,
1019
- agent: k,
1020
- selectedChatModel: _,
1179
+ requestHints: I,
1180
+ agent: D,
1181
+ selectedChatModel: v,
1021
1182
  availableTools: t,
1022
1183
  defaultActiveTools: s
1023
1184
  });
@@ -1030,21 +1191,21 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
1030
1191
  tools: l,
1031
1192
  ignoreIncompleteToolCalls: !0
1032
1193
  });
1033
- await ze(a, p), w && Be(p);
1194
+ await ut(a, p), S && dt(p);
1034
1195
  let h = typeof m.openaiReasoningSummary == "string" ? m.openaiReasoningSummary : null, g;
1035
- w && O ? g = { openai: {
1036
- reasoningEffort: O,
1196
+ S && E ? g = { openai: {
1197
+ reasoningEffort: E,
1037
1198
  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 $({
1199
+ } } : C && o && E && (g = { xai: { reasoningEffort: E } });
1200
+ let _ = !1, y = /* @__PURE__ */ new Date(), b = async ({ status: e, usage: t, finishReason: n, error: r }) => {
1201
+ _ || (_ = !0, await $({
1041
1202
  ctx: a,
1042
- usageContext: j,
1043
- agent: k,
1203
+ usageContext: k,
1204
+ agent: D,
1044
1205
  chatId: f,
1045
1206
  mode: c,
1046
1207
  feature: "chat",
1047
- modelId: _,
1208
+ modelId: v,
1048
1209
  status: e,
1049
1210
  billable: e === "success",
1050
1211
  usage: t,
@@ -1052,17 +1213,17 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
1052
1213
  error: r,
1053
1214
  startedAt: y
1054
1215
  }));
1055
- }, x = C({
1056
- model: ue(_),
1057
- system: fe({
1058
- selectedChatModel: _,
1059
- requestHints: R,
1060
- agentInstructions: k.instructions,
1061
- knowledge: A
1216
+ }, te = oe({
1217
+ model: pe(v),
1218
+ system: he({
1219
+ selectedChatModel: v,
1220
+ requestHints: I,
1221
+ agentInstructions: D.instructions,
1222
+ knowledge: O
1062
1223
  }),
1063
1224
  messages: p,
1064
1225
  tools: l,
1065
- stopWhen: re(5),
1226
+ stopWhen: ae(5),
1066
1227
  abortSignal: V.abortController.signal,
1067
1228
  providerOptions: g,
1068
1229
  activeTools: u,
@@ -1087,16 +1248,16 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
1087
1248
  });
1088
1249
  }
1089
1250
  });
1090
- e.merge(x.toUIMessageStream({
1091
- originalMessages: B,
1092
- sendReasoning: o || !!(w && O)
1251
+ e.merge(te.toUIMessageStream({
1252
+ originalMessages: R,
1253
+ sendReasoning: o || !!(S && E)
1093
1254
  }));
1094
1255
  }
1095
1256
  });
1096
1257
  return (async () => {
1097
1258
  let e = null;
1098
1259
  try {
1099
- let t = pe.getReader();
1260
+ let t = W.getReader();
1100
1261
  for (e = () => t.releaseLock();;) {
1101
1262
  let { value: e, done: n } = await t.read();
1102
1263
  if (n) break;
@@ -1111,24 +1272,24 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
1111
1272
  } finally {
1112
1273
  e?.();
1113
1274
  try {
1114
- await X(a, f);
1275
+ await tt(a, f);
1115
1276
  } catch (e) {
1116
1277
  console.error("Failed to update chat streaming state.", e);
1117
1278
  }
1118
1279
  }
1119
1280
  })(), {};
1120
- }, ct = async (e, t) => st({
1281
+ }, Nt = async (e, t) => Mt({
1121
1282
  payload: e,
1122
1283
  ctx: t,
1123
1284
  mode: "interactive"
1124
- }), lt = async (e, n) => {
1285
+ }), Pt = async (e, n) => {
1125
1286
  let r = n.req.query.id, i = Array.isArray(r) ? r[0] : r;
1126
1287
  return typeof i != "string" || i.trim() === "" ? t(n, "bad_request:api") : f(n, i);
1127
- }, ut = (e) => {
1128
- e.get(J, (async (e, n) => {
1288
+ }, Ft = (e) => {
1289
+ e.get(Je, (async (e, n) => {
1129
1290
  let r = n.req.query.id, i = Array.isArray(r) ? r[0] : r;
1130
1291
  return typeof i != "string" || i.trim() === "" ? t(n, "bad_request:api", "Parameter id is required.") : await o(n, i) || t(n, "not_found:chat");
1131
- })), e.post(J, ct), e.delete(J, lt);
1292
+ })), e.post(Je, Nt), e.delete(Je, Pt);
1132
1293
  };
1133
1294
  //#endregion
1134
- export { ut as default, st as runAgentLoop };
1295
+ export { Ft as default, Mt as runAgentLoop };