@rpcbase/agents-sdk 0.7.0 → 0.9.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 (75) hide show
  1. package/dist/api/chat/handler.d.ts.map +1 -1
  2. package/dist/api/chat/historyCompaction.d.ts +29 -0
  3. package/dist/api/chat/historyCompaction.d.ts.map +1 -0
  4. package/dist/api/chat/models.d.ts +1 -0
  5. package/dist/api/chat/models.d.ts.map +1 -1
  6. package/dist/api/chat/runtimeConfig.d.ts +43 -0
  7. package/dist/api/chat/runtimeConfig.d.ts.map +1 -1
  8. package/dist/api/chatDb.d.ts +4 -0
  9. package/dist/api/chatDb.d.ts.map +1 -1
  10. package/dist/chat-models.browser.js +2 -2
  11. package/dist/chat-models.d.ts +1 -1
  12. package/dist/chat-models.d.ts.map +1 -1
  13. package/dist/chat-models.js +2 -2
  14. package/dist/{chatDb-DdX0Vtyt.js → chatDb-BSiHIyn9.js} +25 -18
  15. package/dist/{chatDb-CcAjAGX7.js → chatDb-YfeABtn-.js} +25 -18
  16. package/dist/client-routes.browser.js +94 -75
  17. package/dist/client-routes.d.ts +7 -1
  18. package/dist/client-routes.d.ts.map +1 -1
  19. package/dist/client-routes.js +94 -75
  20. package/dist/components/agents-chat-route-layout.d.ts +5 -2
  21. package/dist/components/agents-chat-route-layout.d.ts.map +1 -1
  22. package/dist/components/artifact-messages.d.ts +3 -2
  23. package/dist/components/artifact-messages.d.ts.map +1 -1
  24. package/dist/components/artifact.d.ts +6 -2
  25. package/dist/components/artifact.d.ts.map +1 -1
  26. package/dist/components/chat.d.ts +6 -2
  27. package/dist/components/chat.d.ts.map +1 -1
  28. package/dist/components/message.d.ts +3 -2
  29. package/dist/components/message.d.ts.map +1 -1
  30. package/dist/components/messages.d.ts +3 -2
  31. package/dist/components/messages.d.ts.map +1 -1
  32. package/dist/components/multimodal-input.d.ts +4 -1
  33. package/dist/components/multimodal-input.d.ts.map +1 -1
  34. package/dist/components/sidebar-history-item.d.ts +4 -5
  35. package/dist/components/sidebar-history-item.d.ts.map +1 -1
  36. package/dist/components/sidebar-history.d.ts +6 -3
  37. package/dist/components/sidebar-history.d.ts.map +1 -1
  38. package/dist/{data-stream-handler-BW4eCG7d.js → data-stream-handler-DXAHFC5k.js} +462 -427
  39. package/dist/{data-stream-handler-Bd_oM4r9.js → data-stream-handler-lr4wJ3vt.js} +462 -427
  40. package/dist/{handler-D7f8iAy5.js → handler-5n-YwiF3.js} +1 -1
  41. package/dist/{handler-CGV7uuUA.js → handler-B3uUDuTR.js} +1 -1
  42. package/dist/{handler-BLG0AYVC.js → handler-BMeUL2iE.js} +1 -1
  43. package/dist/{handler-C6u7vLAb.js → handler-BgYHL3BZ.js} +9 -9
  44. package/dist/{handler-dVlpopfq.js → handler-By86dyTJ.js} +1 -1
  45. package/dist/{handler-BeWk8pDD.js → handler-C0MO52d9.js} +1 -1
  46. package/dist/{handler-mbDBRYl8.js → handler-C8gaYgmy.js} +1 -1
  47. package/dist/{handler-ClWOGjB_.js → handler-DE8agLBS.js} +438 -268
  48. package/dist/{handler-CEk1hut1.js → handler-DMwBT4bK.js} +1 -1
  49. package/dist/{handler-DPuJK6ft.js → handler-DSncMeo4.js} +352 -182
  50. package/dist/{handler-BY5bgBEh.js → handler-DdKB5P3H.js} +1 -1
  51. package/dist/{handler-BBCbPLLC.js → handler-Dy536I3-.js} +1 -1
  52. package/dist/{handler-BKT8Hl0a.js → handler-Jua6SU39.js} +9 -9
  53. package/dist/{handler-CZSMkZnQ.js → handler-YmuAR8ei.js} +1 -1
  54. package/dist/{handler-P40GjJry.js → handler-hah8tVEE.js} +1 -1
  55. package/dist/{handler-DbjPd3w4.js → handler-svaSKC2q.js} +1 -1
  56. package/dist/index.browser.js +4 -3
  57. package/dist/index.d.ts +2 -0
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +4 -3
  60. package/dist/lib/ai/models.d.ts +6 -0
  61. package/dist/lib/ai/models.d.ts.map +1 -1
  62. package/dist/lib/types.d.ts +23 -0
  63. package/dist/lib/types.d.ts.map +1 -1
  64. package/dist/{models-DUt7W9lV.js → models-DphUIx22.js} +13 -2
  65. package/dist/pages/ChatNewPage.d.ts +6 -1
  66. package/dist/pages/ChatNewPage.d.ts.map +1 -1
  67. package/dist/pages/ChatPage.d.ts +6 -1
  68. package/dist/pages/ChatPage.d.ts.map +1 -1
  69. package/dist/routes.browser.js +8 -8
  70. package/dist/routes.js +8 -8
  71. package/dist/runtime.d.ts +2 -2
  72. package/dist/runtime.d.ts.map +1 -1
  73. package/dist/runtime.js +1 -1
  74. package/dist/tailwind-source.js +1 -1
  75. package/package.json +1 -1
@@ -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";
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 ee } from "./chatDb-YfeABtn-.js";
5
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";
6
+ import { Output as y, convertToModelMessages as te, createUIMessageStream as ne, extractReasoningMiddleware as b, generateText as re, smoothStream as ie, stepCountIs as ae, streamObject as oe, streamText as se, tool as x, wrapLanguageModel as ce } from "ai";
7
+ import { getTenantFilesystemDb as S } from "@rpcbase/db";
8
+ import { createHash as C, randomUUID as w } from "node:crypto";
9
+ import { GridFSBucket as T, ObjectId as le } from "mongodb";
10
+ import { createGoogleGenerativeAI as E } from "@ai-sdk/google";
11
+ import { openai as D } from "@ai-sdk/openai";
12
+ import { createXai as O } from "@ai-sdk/xai";
13
+ import { z as k } 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 A = /-thinking$/, j = "openai/", M = "google/", N = "xai/", P = 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
+ ]), F = (e) => e.startsWith(j), ue = (e) => e.startsWith(M), de = (e) => e.startsWith(N), I = (e) => e.endsWith("-thinking"), fe = (e) => e.includes("/") ? F(e) || ue(e) || de(e) : !1, L = O({
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
+ }), R = E({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY }), pe = (e) => {
24
+ if (F(e)) return D.responses(e.slice(j.length));
25
+ if (ue(e)) {
26
+ let t = e.slice(M.length).replace(A, ""), n = R.chat(t);
27
+ return I(e) ? ce({
28
28
  model: n,
29
- middleware: x({ tagName: "thinking" })
29
+ middleware: b({ 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 (de(e)) {
33
+ let t = e.slice(N.length).replace(A, "");
34
+ return I(e) ? L.responses(t) : L.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 = () => D.chat("gpt-5.4-mini"), z = () => D.chat(process.env.AGENT_SDK_ARTIFACT_MODEL ?? "gpt-5.4-mini"), he = "\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
+ `, ge = ({ 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${he}`;
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", _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", U = (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
+ }, 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", ye = 24, be = 8e4, xe = 16e3, Se = "agent-runtime-history-compaction-summary", W = (e) => !!e && typeof e == "object" && !Array.isArray(e), G = (e) => typeof e == "string" && e.trim() ? e.trim() : null, Ce = (e) => {
57
+ let t = G((W(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
+ }, K = (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
+ }, we = (e) => (Array.isArray(e.parts) ? e.parts : []).flatMap((e) => {
72
+ if (!W(e)) {
73
+ let t = K(e);
74
+ return t ? [t] : [];
75
+ }
76
+ let t = G(e.type) ?? "part", n = K(e.text);
77
+ if (n) return [`${t}: ${n}`];
78
+ let r = K(e.output);
79
+ if (r) return [`${t}: ${r}`];
80
+ let i = K(e.result);
81
+ if (i) return [`${t}: ${i}`];
82
+ let a = K(e.content);
83
+ if (a) return [`${t}: ${a}`];
84
+ let o = K(e, 1e3);
85
+ return o ? [`${t}: ${o}`] : [];
86
+ }).join("\n").trim(), Te = (e) => e.reduce((e, t) => e + we(t).length, 0), Ee = (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
+ }, De = (e) => e ? {
92
+ maxMessages: Number.isFinite(e.maxMessages) && Number(e.maxMessages) > 0 ? Math.floor(Number(e.maxMessages)) : ye,
93
+ maxEstimatedChars: Number.isFinite(e.maxEstimatedChars) && Number(e.maxEstimatedChars) > 0 ? Math.floor(Number(e.maxEstimatedChars)) : be,
94
+ maxSummaryChars: Number.isFinite(e.maxSummaryChars) && Number(e.maxSummaryChars) > 0 ? Math.floor(Number(e.maxSummaryChars)) : xe
95
+ } : {
96
+ maxMessages: ye,
97
+ maxEstimatedChars: be,
98
+ maxSummaryChars: xe
99
+ }, q = (e) => W(e) && e.type === "agent-runtime-history-compaction" && e.version === 1 && typeof e.summary == "string", Oe = (e) => q(e) ? e : W(e) && q(e.historyCompaction) ? e.historyCompaction : null, ke = (e, t) => t ? W(e) && !q(e) ? {
100
+ ...e,
101
+ historyCompaction: t
102
+ } : { historyCompaction: t } : e ?? null, Ae = (e) => G(e.id), je = (e, t) => {
103
+ let n = G(t?.compactedThroughMessageId);
104
+ return n ? e.findIndex((e) => Ae(e) === n) : -1;
105
+ }, Me = (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 && Te(e.slice(i)) > t.maxEstimatedChars;) i += 1;
108
+ return i;
109
+ }, Ne = (e) => {
110
+ let t = G(e.role) ?? "message", n = Ce(e), r = we(e);
111
+ return `${n ? `${t} (${n})` : t}:\n${r || "[non-text content]"}`;
112
+ }, Pe = ({ previousContext: e, messagesToCompact: t, limits: n }) => {
113
+ let r = e?.summary?.trim(), i = t.map(Ne).join("\n\n").trim();
114
+ return Ee([r ? `Earlier summary:\n${r}` : null, i ? `Compacted transcript:\n${i}` : null].filter((e) => !!e).join("\n\n"), n.maxSummaryChars).trim();
115
+ }, Fe = (e) => ({
116
+ id: `${Se}:${G(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
+ }), J = (e, t) => t?.summary.trim() ? [Fe(t), ...e] : e, Ie = ({ messages: e, previousContext: t, limits: n }) => {
133
+ let r = je(e, t), i = r >= 0 ? e.slice(r + 1) : e;
134
+ if (!(i.length > n.maxMessages || Te(i) > n.maxEstimatedChars)) return {
135
+ messages: J(i, t),
136
+ context: t
137
+ };
138
+ let a = Me(i, n);
139
+ if (a <= 0) return {
140
+ messages: J(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: Pe({
147
+ previousContext: t,
148
+ messagesToCompact: o,
149
+ limits: n
150
+ }),
151
+ compactedThroughMessageId: c ? Ae(c) : t?.compactedThroughMessageId ?? null,
152
+ compactedThroughMessageCreatedAt: c ? Ce(c) : t?.compactedThroughMessageCreatedAt ?? null,
153
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
154
+ messageCount: e.length
155
+ };
156
+ return {
157
+ messages: J(s, l),
158
+ context: l
159
+ };
160
+ }, Le = 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 = De(c), u = Oe(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
+ }) : Ie({
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: ke(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
+ }, Re = [
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
+ ], ze = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, Y = () => !ze(process.env.AGENT_SDK_LIVE_TOOLS) && (ze(process.env.PLAYWRIGHT) || process.env.NODE_ENV === "test"), Be = 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 } = se({
209
+ model: z(),
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
+ }, Ve = 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 } = oe({
231
+ model: z(),
93
232
  system: e,
94
233
  prompt: t,
95
- schema: M.object({ code: M.string() })
234
+ schema: k.object({ code: k.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
+ }, He = 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 } = oe({
256
+ model: z(),
118
257
  system: e,
119
258
  prompt: t,
120
- schema: M.object({ csv: M.string().describe("CSV data") })
259
+ schema: k.object({ csv: k.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
+ }, Ue = 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
+ }, We = ({ 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 = x({
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: k.object({
296
+ latitude: k.number().optional(),
297
+ longitude: k.number().optional(),
298
+ city: k.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 Ue(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 = x({
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: k.object({
315
+ title: k.string().describe("The title of the artifact"),
316
+ kind: k.enum(Re).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 = w();
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 Be({
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 Ve({
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 He({
347
+ system: _e,
209
348
  prompt: n,
210
349
  dataStream: t
211
350
  })), await d(e, {
@@ -224,37 +363,37 @@ ${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 = x({
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: k.object({
369
+ id: k.string().describe("The ID of the artifact to rewrite"),
370
+ description: k.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 (!Re.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({
245
- system: W(i.content, i.kind),
383
+ return o === "text" ? s = await Be({
384
+ system: U(i.content, i.kind),
246
385
  prompt: r,
247
386
  dataStream: t,
248
387
  providerOptions: { openai: { prediction: {
249
388
  type: "content",
250
389
  content: i.content
251
390
  } } }
252
- }) : o === "code" ? s = await ye({
253
- system: W(i.content, i.kind),
391
+ }) : o === "code" ? s = await Ve({
392
+ system: U(i.content, i.kind),
254
393
  prompt: r,
255
394
  dataStream: t
256
- }) : o === "sheet" && (s = await be({
257
- system: W(i.content, i.kind),
395
+ }) : o === "sheet" && (s = await He({
396
+ system: U(i.content, i.kind),
258
397
  prompt: r,
259
398
  dataStream: t
260
399
  })), await d(e, {
@@ -277,20 +416,20 @@ ${e}`;
277
416
  return {
278
417
  getWeather: o,
279
418
  createDocument: s,
280
- editDocument: w({
419
+ editDocument: x({
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: k.object({
422
+ id: k.string().describe("The ID of the artifact to edit"),
423
+ old_string: k.string().min(1).describe("Exact string to find. Include enough surrounding context to make the match unique."),
424
+ new_string: k.string().describe("Replacement string"),
425
+ replace_all: k.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 (!Re.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: x({
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: k.object({ documentId: k.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: w(),
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 } = se({
502
+ model: z(),
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: y.array({ element: k.object({
506
+ originalSentence: k.string().describe("The original sentence"),
507
+ suggestedSentence: k.string().describe("The suggested sentence"),
508
+ description: k.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: w(),
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: D.tools.webSearch({
404
543
  externalWebAccess: !0,
405
544
  searchContextSize: "medium",
406
545
  userLocation: {
@@ -410,34 +549,43 @@ ${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
+ }, Ge = (e) => e ? !e.trim() : !0, Ke = (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(), qe = (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
+ }, Je = (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) => {
560
+ return !t || Je(t) ? "" : qe(t.replaceAll("\n", " ").replaceAll("\r", " ").split(/\s+/).filter((e) => e.trim() !== "").slice(0, 5).join(" "));
561
+ }, Ye = "/api/rb/agents/chat";
562
+ k.any(), k.any();
563
+ var Xe = 1024 * 1024 * 20, Ze = 1e5, Qe = /^\/api\/rb\/files\/([^/]+)\/?$/, $e = "test-model", et = "openai/gpt-5.4-mini", tt = async (e) => new Promise((t) => setTimeout(t, e)), nt = async (e, t) => {
425
564
  let n = _(t);
426
- n && !n.isDone || await g(e, {
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
+ }, rt = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, Z = (e) => typeof e == "string" && e.trim() || null, it = () => {
570
+ let e = r().chatModels;
571
+ if (!e?.length) return P;
572
+ let t = /* @__PURE__ */ new Set();
573
+ for (let n of e) {
574
+ let e = Z(typeof n == "string" ? n : n.id);
575
+ e && t.add(e);
576
+ }
577
+ return t;
578
+ }, at = (e) => {
431
579
  if (typeof e == "boolean") return e;
432
580
  let t = Z(e)?.toLowerCase();
433
581
  return t ? t === "true" ? !0 : t === "false" ? !1 : null : null;
434
- }, Ne = (e) => {
582
+ }, ot = (e) => {
435
583
  let t = e.req?.session?.user?.currentTenantId;
436
584
  return Z(t);
437
- }, Pe = (e) => {
585
+ }, st = (e) => {
438
586
  let t = e.req?.session?.user?.id;
439
587
  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) => {
588
+ }, ct = () => Z(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", lt = (e) => C("sha256").update(Buffer.from(e)).digest("hex"), ut = (e) => {
441
589
  let t = e.trim();
442
590
  if (!t) return null;
443
591
  let n;
@@ -450,36 +598,36 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
450
598
  return null;
451
599
  }
452
600
  }
453
- let r = Oe.exec(n.pathname);
601
+ let r = Qe.exec(n.pathname);
454
602
  if (!r) return null;
455
603
  let i = Z(decodeURIComponent(r[1]));
456
604
  return i ? {
457
605
  fileId: i,
458
606
  uploadKey: Z(n.searchParams.get("rb-upload-key"))
459
607
  } : null;
460
- }, Re = async ({ ctx: e, fileId: t, uploadKey: n }) => {
461
- let r = Ne(e);
608
+ }, dt = async ({ ctx: e, fileId: t, uploadKey: n }) => {
609
+ let r = ot(e);
462
610
  if (!r) throw Error("tenant_missing");
463
611
  let i;
464
612
  try {
465
- i = new ae(t);
613
+ i = new le(t);
466
614
  } catch {
467
615
  throw Error("invalid_file_id");
468
616
  }
469
- let a = (await T(r)).db;
617
+ let a = (await S(r)).db;
470
618
  if (!a) throw Error("filesystem_db_unavailable");
471
- let o = new O(a, { bucketName: Fe() }), [s] = await o.find({ _id: i }).limit(1).toArray();
619
+ let o = new T(a, { bucketName: ct() }), [s] = await o.find({ _id: i }).limit(1).toArray();
472
620
  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);
621
+ let c = at(s?.metadata?.isPublic) ?? !1, l = st(e), u = Z(s?.metadata?.userId), d = Z(s?.metadata?.ownerKeyHash);
474
622
  if (!c) {
475
- let e = !!(l && u && l === u), t = !!(n && d && Ie(n) === d);
623
+ let e = !!(l && u && l === u), t = !!(n && d && lt(n) === d);
476
624
  if (!e && !t) throw Error("unauthorized");
477
625
  }
478
626
  let f = Z(s?.metadata?.mimeType), p = [], m = 0;
479
627
  return await new Promise((e, t) => {
480
628
  let n = o.openDownloadStream(i);
481
629
  n.on("data", (e) => {
482
- if (m += e.length, m > Ee) {
630
+ if (m += e.length, m > Xe) {
483
631
  n.destroy(/* @__PURE__ */ Error("attachment_too_large"));
484
632
  return;
485
633
  }
@@ -489,16 +637,16 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
489
637
  data: Buffer.concat(p, m),
490
638
  mimeType: f
491
639
  };
492
- }, ze = async (e, t) => {
640
+ }, ft = async (e, t) => {
493
641
  let n = Array.isArray(t) ? t : [], r = [];
494
642
  for (let t of n) {
495
643
  if (!t || typeof t != "object" || !("role" in t) || t.role !== "user") continue;
496
644
  let n = Array.isArray(t.content) ? t.content : null;
497
645
  if (n) for (let t of n) {
498
646
  if (!t || typeof t != "object" || t.type !== "file" || typeof t.data != "string") continue;
499
- let n = Le(t.data);
647
+ let n = ut(t.data);
500
648
  n && r.push((async () => {
501
- let { data: r, mimeType: i } = await Re({
649
+ let { data: r, mimeType: i } = await dt({
502
650
  ctx: e,
503
651
  ...n
504
652
  });
@@ -507,7 +655,7 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
507
655
  }
508
656
  }
509
657
  r.length > 0 && await Promise.all(r);
510
- }, Be = (e) => {
658
+ }, pt = (e) => {
511
659
  let t = Array.isArray(e) ? e : [];
512
660
  for (let e of t) {
513
661
  if (!e || typeof e != "object" || !("role" in e) || e.role !== "user") continue;
@@ -520,7 +668,7 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
520
668
  let i = Z(n.filename) ?? Z(n.name) ?? `attachment-${e + 1}`, a = n.data;
521
669
  if (r?.startsWith("text/") && a instanceof Uint8Array) {
522
670
  let n = (Buffer.isBuffer(a) ? a : Buffer.from(a)).toString("utf8");
523
- n.length > De && (n = `${n.slice(0, De)}\n\n[Truncated]`);
671
+ n.length > Ze && (n = `${n.slice(0, Ze)}\n\n[Truncated]`);
524
672
  let o = r === "text/csv" || i.toLowerCase().endsWith(".csv") ? "csv" : "";
525
673
  t[e] = {
526
674
  type: "text",
@@ -535,16 +683,16 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
535
683
  };
536
684
  }
537
685
  }
538
- }, Ve = async (e, t, n) => {
539
- if (e.message?.role === "user") return K(e.message.parts);
686
+ }, mt = async (e, t, n) => {
687
+ if (e.message?.role === "user") return Ke(e.message.parts);
540
688
  if (Array.isArray(e.messages)) {
541
689
  let t = null;
542
690
  for (let n = e.messages.length - 1; n >= 0; --n) {
543
691
  let r = e.messages[n];
544
692
  if (r?.role !== "user") continue;
545
- let i = K(r.parts);
693
+ let i = Ke(r.parts);
546
694
  if (i) {
547
- if (q(i)) return i;
695
+ if (X(i)) return i;
548
696
  t ??= i;
549
697
  }
550
698
  }
@@ -554,40 +702,40 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
554
702
  for (let e = r.length - 1; e >= 0; --e) {
555
703
  let t = r[e];
556
704
  if (t.role !== "user") continue;
557
- let n = K(t.parts);
705
+ let n = Ke(t.parts);
558
706
  if (n) {
559
- if (q(n)) return n;
707
+ if (X(n)) return n;
560
708
  i ??= n;
561
709
  }
562
710
  }
563
711
  return i ?? "";
564
- }, He = (e) => {
712
+ }, ht = (e) => {
565
713
  let t = Array.isArray(e.messages) && e.messages.length > 0 ? e.messages.at(-1) : e.message;
566
714
  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) => {
715
+ }, gt = (e) => {
568
716
  let t = e.id;
569
717
  return typeof t == "string" && t.trim() !== "" ? t : null;
570
- }, We = (e) => {
718
+ }, _t = (e) => {
571
719
  let t = e.selectedChatModel;
572
720
  return typeof t == "string" && t.trim() !== "" ? t : null;
573
- }, Ge = (e) => {
721
+ }, vt = (e) => {
574
722
  let t = e.openaiReasoningEffort;
575
723
  return typeof t == "string" && t.trim() !== "" ? t.trim() : null;
576
- }, Ke = (e) => {
724
+ }, yt = (e) => {
577
725
  if (!e || typeof e != "object") return !1;
578
726
  let t = e.state, n = e.toolCallId;
579
727
  return typeof n == "string" && n.trim() !== "" && (t === "approval-responded" || t === "output-denied");
580
- }, qe = (e) => {
728
+ }, bt = (e) => {
581
729
  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) => {
730
+ return t.length === 0 || t.at(-1)?.role === "user" ? !1 : t.some((e) => (Array.isArray(e?.parts) ? e.parts : []).some((e) => yt(e)));
731
+ }, xt = (e) => {
584
732
  let t = /* @__PURE__ */ new Map();
585
733
  for (let n of e) {
586
734
  let e = Array.isArray(n?.parts) ? n.parts : [];
587
- for (let n of e) Ke(n) && t.set(n.toolCallId, n);
735
+ for (let n of e) yt(n) && t.set(n.toolCallId, n);
588
736
  }
589
737
  return t;
590
- }, Ye = (e, t) => {
738
+ }, St = (e, t) => {
591
739
  let n = [];
592
740
  return {
593
741
  changedMessages: n,
@@ -610,21 +758,21 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
610
758
  return n.push(a), a;
611
759
  })
612
760
  };
613
- }, Xe = (e) => {
761
+ }, Ct = (e) => {
614
762
  if (!e || typeof e != "object" || !("createdAt" in e)) return null;
615
763
  let t = e.createdAt;
616
764
  if (typeof t != "string") return null;
617
765
  let n = new Date(t);
618
766
  return Number.isNaN(n.getTime()) ? null : n;
619
- }, Ze = (e) => ({
767
+ }, wt = (e) => ({
620
768
  latitude: null,
621
769
  longitude: null,
622
770
  city: null,
623
771
  country: null
624
- }), Qe = (e) => {
772
+ }), Tt = (e) => {
625
773
  let [t] = e.split("/");
626
774
  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) => {
775
+ }, Q = (e) => typeof e == "number" && Number.isFinite(e) ? e : void 0, Et = (e) => e instanceof Error && e.message.trim() ? e.message : "Unknown error", Dt = (e) => {
628
776
  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
777
  return {
630
778
  inputTokens: Q(t.inputTokens),
@@ -634,13 +782,13 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
634
782
  reasoningTokens: Q(r.reasoningTokens) ?? Q(t.reasoningTokens),
635
783
  rawUsage: Object.keys(t).length > 0 ? t.raw ?? t : void 0
636
784
  };
637
- }, tt = () => ({
785
+ }, Ot = () => ({
638
786
  inputTokens: 0,
639
787
  outputTokens: 0,
640
788
  totalTokens: 0,
641
789
  cachedInputTokens: 0,
642
790
  reasoningTokens: 0
643
- }), nt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a }) => {
791
+ }), kt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a }) => {
644
792
  try {
645
793
  return { workspaceId: Z((await r().resolveUsageContext?.({
646
794
  ctx: e,
@@ -653,19 +801,19 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
653
801
  return console.warn("Failed to resolve agent usage context.", e), { workspaceId: void 0 };
654
802
  }
655
803
  }, $ = 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(),
804
+ let h = u ? Dt(u) : {}, g = {
805
+ id: w(),
658
806
  workspaceId: t.workspaceId,
659
807
  agentId: n.id,
660
808
  chatId: r,
661
809
  mode: i,
662
810
  feature: o,
663
- provider: Qe(s),
811
+ provider: Tt(s),
664
812
  model: s,
665
813
  billable: l,
666
814
  status: c,
667
815
  finishReason: Z(d) ?? void 0,
668
- errorMessage: f ? $e(f) : void 0,
816
+ errorMessage: f ? Et(f) : void 0,
669
817
  ...h,
670
818
  startedAt: p,
671
819
  finishedAt: m,
@@ -676,12 +824,12 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
676
824
  } catch (e) {
677
825
  console.error("Failed to save agents usage event.", e);
678
826
  }
679
- }, rt = (e) => `agents-sdk:chat:${e}:stream`, it = async ({ ctx: e, chatId: t, selectedChatModel: i }) => await r().resolveAgent?.({
827
+ }, At = (e) => `agents-sdk:chat:${e}:stream`, jt = async ({ ctx: e, chatId: t, selectedChatModel: i }) => await r().resolveAgent?.({
680
828
  ctx: e,
681
829
  chatId: t,
682
830
  selectedChatModel: i
683
- }) ?? n(), at = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
684
- let a = i(e), o = rt(t), s = v({
831
+ }) ?? n(), Mt = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
832
+ let a = i(e), o = At(t), s = v({
685
833
  chatId: t,
686
834
  abortWhenNoSubscribersMs: n === "headless" || r ? 0 : void 0
687
835
  });
@@ -709,95 +857,95 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
709
857
  });
710
858
  }
711
859
  };
712
- }, ot = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
860
+ }, Nt = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
713
861
  if (!n) return;
714
862
  let a = i(e);
715
863
  n.publish({
716
864
  tenantId: a.tenantId,
717
865
  userId: a.userId,
718
- channel: rt(t),
866
+ channel: At(t),
719
867
  payload: {
720
868
  chatId: t,
721
869
  message: r
722
870
  }
723
871
  });
724
- }, st = async ({ payload: n, ctx: a, mode: c = "interactive", streamTransport: d = null }) => {
725
- let f = Ue(n);
872
+ }, Pt = async ({ payload: n, ctx: a, mode: c = "interactive", streamTransport: d = null }) => {
873
+ let f = gt(n);
726
874
  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";
875
+ let m = n, _ = _t(m), v = rt(process.env.PLAYWRIGHT), y = !rt(process.env.AGENT_SDK_LIVE_CHAT) && v || process.env.NODE_ENV === "test";
728
876
  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({
877
+ if (_ === $e && (y = !0), _ !== $e && (!it().has(_) || !fe(_))) return t(a, "bad_request:api", `Unsupported selectedChatModel: "${_}".`);
878
+ let b = process.env.OPENAI_API_KEY, ie = process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY, oe = process.env.XAI_API_KEY, x = F(_), ce = ue(_), S = de(_), C = vt(m), T = C && C !== "default" && C !== "off" ? C : null, le = e(_);
879
+ if (T && !le.some((e) => e === T)) return t(a, "bad_request:api", `Unsupported reasoning effort "${T}" for selectedChatModel: "${_}".`);
880
+ if (!y && x && !b) return t(a, "bad_request:provider", "Missing OPENAI_API_KEY.");
881
+ if (!y && ce && !ie) return t(a, "bad_request:provider", "Missing GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY).");
882
+ if (!y && S && !oe) return t(a, "bad_request:provider", "Missing XAI_API_KEY.");
883
+ if (!y && !x && !ce && !S) return t(a, "bad_request:provider", `Unsupported selectedChatModel: "${_}".`);
884
+ let E = await jt({
737
885
  ctx: a,
738
886
  chatId: f,
739
887
  selectedChatModel: _
740
- }), A = await r().resolveKnowledge?.({
888
+ }), D = await r().resolveKnowledge?.({
741
889
  ctx: a,
742
890
  chatId: f,
743
- agent: k,
891
+ agent: E,
744
892
  selectedChatModel: _
745
- }) ?? null, j = await nt({
893
+ }) ?? null, O = await kt({
746
894
  ctx: a,
747
895
  chatId: f,
748
- agent: k,
896
+ agent: E,
749
897
  selectedChatModel: _,
750
898
  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, {
899
+ }), k = i(a), A = await o(a, f, { includeDeleted: !0 });
900
+ if (A?.deletedAt) return t(a, "not_found:chat");
901
+ A ? A.selectedChatModel !== _ && await ee(a, {
754
902
  chatId: f,
755
903
  selectedChatModel: _
756
904
  }) : await p(a, {
757
905
  id: f,
758
906
  createdAt: /* @__PURE__ */ new Date(),
759
- userId: M.userId,
907
+ userId: k.userId,
760
908
  title: "",
761
909
  isStreaming: !1,
762
910
  selectedChatModel: _,
763
911
  lastContext: null
764
912
  });
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") {
913
+ let j = m.message, M = typeof j?.id == "string" ? j.id : w(), N = Array.isArray(j?.parts) ? j?.parts : [];
914
+ if ((typeof j?.role == "string" ? j.role : null) === "user") {
767
915
  let e = /* @__PURE__ */ new Date();
768
916
  await l(a, [{
769
- id: F,
917
+ id: M,
770
918
  chatId: f,
771
919
  role: "user",
772
- parts: I,
920
+ parts: N,
773
921
  attachments: [],
774
922
  createdAt: e
775
- }]), ot({
923
+ }]), Nt({
776
924
  ctx: a,
777
925
  chatId: f,
778
926
  streamTransport: d,
779
927
  message: {
780
- id: F,
928
+ id: M,
781
929
  role: "user",
782
- parts: I,
930
+ parts: N,
783
931
  metadata: { createdAt: e.toISOString() }
784
932
  }
785
933
  });
786
934
  }
787
935
  if (y) {
788
- await g(a, {
936
+ await s(a, {
789
937
  chatId: f,
790
938
  isStreaming: !0
791
939
  });
792
- let e = at({
940
+ let e = Mt({
793
941
  ctx: a,
794
942
  chatId: f,
795
943
  mode: c,
796
944
  streamTransport: d
797
945
  });
798
946
  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, {
947
+ let t = X(await mt(m, a, f)), n = await o(a, f);
948
+ n && Ge(n.title) && t && t !== n.title && (await g(a, {
801
949
  chatId: f,
802
950
  title: t
803
951
  }), e.publishJson({
@@ -805,8 +953,8 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
805
953
  data: t,
806
954
  transient: !0
807
955
  }));
808
- let r = D();
809
- v && !e.abortController.signal.aborted && await Y(600), e.publishJson({
956
+ let r = w();
957
+ v && !e.abortController.signal.aborted && await tt(600), e.publishJson({
810
958
  type: "start",
811
959
  messageId: r
812
960
  });
@@ -815,18 +963,18 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
815
963
  type: "text-start",
816
964
  id: i
817
965
  });
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) {
966
+ let s = ht(m), u = s ? `Echo: ${s}` : "Hello from agents-sdk", d = Date.now(), p = u.split(/(\s+)/).filter((e) => e.length > 0);
967
+ for (let t of p) {
820
968
  if (e.abortController.signal.aborted) break;
821
969
  e.publishJson({
822
970
  type: "text-delta",
823
971
  id: i,
824
972
  delta: t
825
- }), await Y(v ? 120 : 80);
973
+ }), await tt(v ? 120 : 80);
826
974
  }
827
975
  if (v && !e.abortController.signal.aborted) {
828
- let e = Date.now() - p, t = 1200;
829
- e < t && await Y(t - e);
976
+ let e = Date.now() - d, t = 1200;
977
+ e < t && await tt(t - e);
830
978
  }
831
979
  return e.abortController.signal.aborted ? {} : (e.publishJson({
832
980
  type: "text-end",
@@ -840,30 +988,30 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
840
988
  role: "assistant",
841
989
  parts: [{
842
990
  type: "text",
843
- text: d
991
+ text: u
844
992
  }],
845
993
  attachments: [],
846
994
  createdAt: /* @__PURE__ */ new Date()
847
995
  }]), await $({
848
996
  ctx: a,
849
- usageContext: j,
850
- agent: k,
997
+ usageContext: O,
998
+ agent: E,
851
999
  chatId: f,
852
1000
  mode: c,
853
1001
  feature: "chat",
854
1002
  modelId: _,
855
1003
  status: "success",
856
1004
  billable: !1,
857
- usage: tt(),
1005
+ usage: Ot(),
858
1006
  finishReason: "stop",
859
- startedAt: new Date(p)
1007
+ startedAt: new Date(d)
860
1008
  }), {});
861
1009
  } finally {
862
- await X(a, f);
1010
+ await nt(a, f);
863
1011
  }
864
1012
  }
865
- let R = Ze(a), z = qe(m);
866
- if (Array.isArray(m.messages) && !z) {
1013
+ let P = wt(a), L = bt(m);
1014
+ if (Array.isArray(m.messages) && !L) {
867
1015
  let e = m.messages.flatMap((e) => {
868
1016
  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
1017
  return !t || !n ? [] : [{
@@ -872,79 +1020,101 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
872
1020
  role: n,
873
1021
  parts: r,
874
1022
  attachments: [],
875
- createdAt: Xe(e?.metadata) ?? /* @__PURE__ */ new Date()
1023
+ createdAt: Ct(e?.metadata) ?? /* @__PURE__ */ new Date()
876
1024
  }];
877
1025
  });
878
1026
  e.length > 0 && await l(a, e);
879
1027
  }
880
- let B;
881
- if (Array.isArray(m.messages) && m.messages.length > 0 && z) {
1028
+ let R;
1029
+ if (Array.isArray(m.messages) && m.messages.length > 0 && L) {
882
1030
  let e = await u(a, f);
883
- if (e.length === 0) B = m.messages;
1031
+ if (e.length === 0) R = m.messages;
884
1032
  else {
885
- let { changedMessages: t, updatedMessages: n } = Ye(e, Je(m.messages));
886
- t.length > 0 && await l(a, t), B = n.map((e) => ({
1033
+ let { changedMessages: t, updatedMessages: n } = St(e, xt(m.messages));
1034
+ t.length > 0 && await l(a, t), R = n.map((e) => ({
887
1035
  id: e.id,
888
1036
  role: e.role,
889
1037
  parts: e.parts,
890
1038
  metadata: { createdAt: e.createdAt.toISOString() }
891
1039
  }));
892
1040
  }
893
- } else B = Array.isArray(m.messages) && m.messages.length > 0 ? m.messages : (await u(a, f)).map((e) => ({
1041
+ } else R = Array.isArray(m.messages) && m.messages.length > 0 ? m.messages : (await u(a, f)).map((e) => ({
894
1042
  id: e.id,
895
1043
  role: e.role,
896
1044
  parts: e.parts,
897
1045
  metadata: { createdAt: e.createdAt.toISOString() }
898
1046
  }));
899
- await g(a, {
1047
+ let z = L ? {
1048
+ messages: R,
1049
+ lastContext: A?.lastContext ?? null,
1050
+ lastContextChanged: !1
1051
+ } : await Le({
1052
+ ctx: a,
1053
+ chatId: f,
1054
+ agent: E,
1055
+ selectedChatModel: _,
1056
+ mode: c,
1057
+ messages: R,
1058
+ lastContext: A?.lastContext ?? null
1059
+ });
1060
+ if (!L && z.lastContextChanged) try {
1061
+ await h(a, {
1062
+ chatId: f,
1063
+ lastContext: z.lastContext
1064
+ });
1065
+ } catch (e) {
1066
+ console.warn("Failed to save compacted agent chat history context.", e);
1067
+ }
1068
+ let he = z.messages;
1069
+ await s(a, {
900
1070
  chatId: f,
901
1071
  isStreaming: !0
902
1072
  });
903
- let V = at({
1073
+ let B = Mt({
904
1074
  ctx: a,
905
1075
  chatId: f,
906
1076
  mode: c,
907
1077
  streamTransport: d
908
- }), H = "", U = "";
1078
+ }), V = "", H = "";
909
1079
  try {
910
- H = await Ve(m, a, f), U = q(H);
1080
+ V = await mt(m, a, f), H = X(V);
911
1081
  let e = await o(a, f);
912
- e && Ce(e.title) && U && U !== e.title && (await s(a, {
1082
+ e && Ge(e.title) && H && H !== e.title && (await g(a, {
913
1083
  chatId: f,
914
- title: U
915
- }), V.publishJson({
1084
+ title: H
1085
+ }), B.publishJson({
916
1086
  type: "data-chat-title",
917
- data: U,
1087
+ data: H,
918
1088
  transient: !0
919
1089
  }));
920
1090
  } catch (e) {
921
- console.error(e), V.publishJson({
1091
+ console.error(e), B.publishJson({
922
1092
  type: "error",
923
1093
  errorText: "Something went wrong."
924
- }), V.publishDone();
1094
+ }), B.publishDone();
925
1095
  try {
926
- await X(a, f);
1096
+ await nt(a, f);
927
1097
  } catch (e) {
928
1098
  console.error("Failed to update chat streaming state.", e);
929
1099
  }
930
1100
  return {};
931
1101
  }
932
- H && U && x && (async () => {
1102
+ V && H && b && (async () => {
933
1103
  let e = /* @__PURE__ */ new Date();
934
1104
  try {
935
- let { text: t } = await te({
936
- model: de(),
937
- system: he,
938
- prompt: H,
1105
+ let { text: t } = await re({
1106
+ model: me(),
1107
+ system: ve,
1108
+ prompt: V,
939
1109
  onFinish: async (t) => {
940
1110
  await $({
941
1111
  ctx: a,
942
- usageContext: j,
943
- agent: k,
1112
+ usageContext: O,
1113
+ agent: E,
944
1114
  chatId: f,
945
1115
  mode: c,
946
1116
  feature: "title",
947
- modelId: Ae,
1117
+ modelId: et,
948
1118
  status: "success",
949
1119
  billable: !0,
950
1120
  usage: t.totalUsage ?? t.usage,
@@ -952,14 +1122,14 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
952
1122
  startedAt: e
953
1123
  });
954
1124
  }
955
- }), n = we(t);
1125
+ }), n = qe(t);
956
1126
  if (!n) return;
957
1127
  let r = await o(a, f);
958
1128
  if (!r) return;
959
- r.title !== n && (await s(a, {
1129
+ r.title !== n && (await g(a, {
960
1130
  chatId: f,
961
1131
  title: n
962
- }), V.publishJson({
1132
+ }), B.publishJson({
963
1133
  type: "data-chat-title",
964
1134
  data: n,
965
1135
  transient: !0
@@ -967,12 +1137,12 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
967
1137
  } catch (t) {
968
1138
  await $({
969
1139
  ctx: a,
970
- usageContext: j,
971
- agent: k,
1140
+ usageContext: O,
1141
+ agent: E,
972
1142
  chatId: f,
973
1143
  mode: c,
974
1144
  feature: "title",
975
- modelId: Ae,
1145
+ modelId: et,
976
1146
  status: "error",
977
1147
  billable: !1,
978
1148
  error: t,
@@ -980,13 +1150,13 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
980
1150
  }), console.warn("Failed to generate chat title.", t);
981
1151
  }
982
1152
  })();
983
- let pe = b({
984
- originalMessages: B,
1153
+ let _e = ne({
1154
+ originalMessages: R,
985
1155
  onError: (e) => (console.error(e), "Something went wrong."),
986
1156
  onFinish: async ({ responseMessage: e }) => {
987
1157
  let t = Array.isArray(e.parts) ? e.parts : [];
988
1158
  await l(a, [{
989
- id: e.id ?? D(),
1159
+ id: e.id ?? w(),
990
1160
  chatId: f,
991
1161
  role: e.role ?? "assistant",
992
1162
  parts: t,
@@ -995,10 +1165,10 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
995
1165
  }]);
996
1166
  },
997
1167
  execute: async ({ writer: e }) => {
998
- let t = Se({
1168
+ let t = We({
999
1169
  ctx: a,
1000
1170
  dataStream: e,
1001
- requestHints: R
1171
+ requestHints: P
1002
1172
  }), n = [
1003
1173
  "getWeather",
1004
1174
  "createDocument",
@@ -1012,17 +1182,17 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
1012
1182
  "editDocument",
1013
1183
  "updateDocument",
1014
1184
  "requestSuggestions"
1015
- ], o = L(_), s = o ? [] : w ? n : i, l = t, u = s, d = await r().resolveTools?.({
1185
+ ], o = I(_), s = o ? [] : x ? n : i, l = t, u = s, d = await r().resolveTools?.({
1016
1186
  ctx: a,
1017
1187
  dataStream: e,
1018
- requestHints: R,
1019
- agent: k,
1188
+ requestHints: P,
1189
+ agent: E,
1020
1190
  selectedChatModel: _,
1021
1191
  availableTools: t,
1022
1192
  defaultActiveTools: s
1023
1193
  });
1024
1194
  d && (l = d.tools, u = d.activeTools ?? Object.keys(d.tools));
1025
- let p = await ee(B.map((e) => ({
1195
+ let p = await te(he.map((e) => ({
1026
1196
  role: e?.role,
1027
1197
  parts: e?.parts,
1028
1198
  metadata: e?.metadata
@@ -1030,17 +1200,17 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
1030
1200
  tools: l,
1031
1201
  ignoreIncompleteToolCalls: !0
1032
1202
  });
1033
- await ze(a, p), w && Be(p);
1203
+ await ft(a, p), x && pt(p);
1034
1204
  let h = typeof m.openaiReasoningSummary == "string" ? m.openaiReasoningSummary : null, g;
1035
- w && O ? g = { openai: {
1036
- reasoningEffort: O,
1205
+ x && T ? g = { openai: {
1206
+ reasoningEffort: T,
1037
1207
  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 $({
1208
+ } } : S && o && T && (g = { xai: { reasoningEffort: T } });
1209
+ let ee = !1, v = /* @__PURE__ */ new Date(), y = async ({ status: e, usage: t, finishReason: n, error: r }) => {
1210
+ ee || (ee = !0, await $({
1041
1211
  ctx: a,
1042
- usageContext: j,
1043
- agent: k,
1212
+ usageContext: O,
1213
+ agent: E,
1044
1214
  chatId: f,
1045
1215
  mode: c,
1046
1216
  feature: "chat",
@@ -1050,85 +1220,85 @@ var Ee = 1024 * 1024 * 20, De = 1e5, Oe = /^\/api\/rb\/files\/([^/]+)\/?$/, ke =
1050
1220
  usage: t,
1051
1221
  finishReason: n,
1052
1222
  error: r,
1053
- startedAt: y
1223
+ startedAt: v
1054
1224
  }));
1055
- }, x = C({
1056
- model: ue(_),
1057
- system: fe({
1225
+ }, ne = se({
1226
+ model: pe(_),
1227
+ system: ge({
1058
1228
  selectedChatModel: _,
1059
- requestHints: R,
1060
- agentInstructions: k.instructions,
1061
- knowledge: A
1229
+ requestHints: P,
1230
+ agentInstructions: E.instructions,
1231
+ knowledge: D
1062
1232
  }),
1063
1233
  messages: p,
1064
1234
  tools: l,
1065
- stopWhen: re(5),
1066
- abortSignal: V.abortController.signal,
1235
+ stopWhen: ae(5),
1236
+ abortSignal: B.abortController.signal,
1067
1237
  providerOptions: g,
1068
1238
  activeTools: u,
1069
1239
  onFinish: async (e) => {
1070
- await b({
1240
+ await y({
1071
1241
  status: "success",
1072
1242
  usage: e.totalUsage ?? e.usage,
1073
1243
  finishReason: e.finishReason
1074
1244
  });
1075
1245
  },
1076
1246
  onError: async (e) => {
1077
- await b({
1247
+ await y({
1078
1248
  status: "error",
1079
1249
  error: e?.error ?? e
1080
1250
  });
1081
1251
  },
1082
1252
  onAbort: async (e) => {
1083
- await b({
1253
+ await y({
1084
1254
  status: "aborted",
1085
1255
  usage: e?.totalUsage ?? e?.usage,
1086
1256
  finishReason: e?.finishReason
1087
1257
  });
1088
1258
  }
1089
1259
  });
1090
- e.merge(x.toUIMessageStream({
1091
- originalMessages: B,
1092
- sendReasoning: o || !!(w && O)
1260
+ e.merge(ne.toUIMessageStream({
1261
+ originalMessages: R,
1262
+ sendReasoning: o || !!(x && T)
1093
1263
  }));
1094
1264
  }
1095
1265
  });
1096
1266
  return (async () => {
1097
1267
  let e = null;
1098
1268
  try {
1099
- let t = pe.getReader();
1269
+ let t = _e.getReader();
1100
1270
  for (e = () => t.releaseLock();;) {
1101
1271
  let { value: e, done: n } = await t.read();
1102
1272
  if (n) break;
1103
- V.publishJson(e);
1273
+ B.publishJson(e);
1104
1274
  }
1105
- V.publishDone();
1275
+ B.publishDone();
1106
1276
  } catch (e) {
1107
- console.error(e), V.publishJson({
1277
+ console.error(e), B.publishJson({
1108
1278
  type: "error",
1109
1279
  errorText: "Something went wrong."
1110
- }), V.publishDone();
1280
+ }), B.publishDone();
1111
1281
  } finally {
1112
1282
  e?.();
1113
1283
  try {
1114
- await X(a, f);
1284
+ await nt(a, f);
1115
1285
  } catch (e) {
1116
1286
  console.error("Failed to update chat streaming state.", e);
1117
1287
  }
1118
1288
  }
1119
1289
  })(), {};
1120
- }, ct = async (e, t) => st({
1290
+ }, Ft = async (e, t) => Pt({
1121
1291
  payload: e,
1122
1292
  ctx: t,
1123
1293
  mode: "interactive"
1124
- }), lt = async (e, n) => {
1294
+ }), It = async (e, n) => {
1125
1295
  let r = n.req.query.id, i = Array.isArray(r) ? r[0] : r;
1126
1296
  return typeof i != "string" || i.trim() === "" ? t(n, "bad_request:api") : f(n, i);
1127
- }, ut = (e) => {
1128
- e.get(J, (async (e, n) => {
1297
+ }, Lt = (e) => {
1298
+ e.get(Ye, (async (e, n) => {
1129
1299
  let r = n.req.query.id, i = Array.isArray(r) ? r[0] : r;
1130
1300
  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);
1301
+ })), e.post(Ye, Ft), e.delete(Ye, It);
1132
1302
  };
1133
1303
  //#endregion
1134
- export { ut as default, st as runAgentLoop };
1304
+ export { Lt as default, Pt as runAgentLoop };