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