@rpcbase/agents-sdk 0.8.0 → 0.10.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 (55) hide show
  1. package/dist/api/chat/handler.d.ts.map +1 -1
  2. package/dist/api/chat/models.d.ts +1 -0
  3. package/dist/api/chat/models.d.ts.map +1 -1
  4. package/dist/api/chat/runtimeConfig.d.ts +4 -0
  5. package/dist/api/chat/runtimeConfig.d.ts.map +1 -1
  6. package/dist/chat-models.browser.js +2 -2
  7. package/dist/chat-models.d.ts +1 -1
  8. package/dist/chat-models.d.ts.map +1 -1
  9. package/dist/chat-models.js +2 -2
  10. package/dist/client-routes.browser.js +94 -75
  11. package/dist/client-routes.d.ts +7 -1
  12. package/dist/client-routes.d.ts.map +1 -1
  13. package/dist/client-routes.js +94 -75
  14. package/dist/components/agents-chat-route-layout.d.ts +5 -2
  15. package/dist/components/agents-chat-route-layout.d.ts.map +1 -1
  16. package/dist/components/artifact-messages.d.ts +3 -2
  17. package/dist/components/artifact-messages.d.ts.map +1 -1
  18. package/dist/components/artifact.d.ts +6 -2
  19. package/dist/components/artifact.d.ts.map +1 -1
  20. package/dist/components/chat.d.ts +6 -2
  21. package/dist/components/chat.d.ts.map +1 -1
  22. package/dist/components/message.d.ts +3 -2
  23. package/dist/components/message.d.ts.map +1 -1
  24. package/dist/components/messages.d.ts +3 -2
  25. package/dist/components/messages.d.ts.map +1 -1
  26. package/dist/components/multimodal-input.d.ts +4 -1
  27. package/dist/components/multimodal-input.d.ts.map +1 -1
  28. package/dist/components/sidebar-history-item.d.ts +4 -5
  29. package/dist/components/sidebar-history-item.d.ts.map +1 -1
  30. package/dist/components/sidebar-history.d.ts +6 -3
  31. package/dist/components/sidebar-history.d.ts.map +1 -1
  32. package/dist/{data-stream-handler-BW4eCG7d.js → data-stream-handler-DXAHFC5k.js} +462 -427
  33. package/dist/{data-stream-handler-Bd_oM4r9.js → data-stream-handler-lr4wJ3vt.js} +462 -427
  34. package/dist/{handler-C06ydMqf.js → handler-DE8agLBS.js} +313 -304
  35. package/dist/{handler-DGbBgIt2.js → handler-DSncMeo4.js} +207 -198
  36. package/dist/index.browser.js +4 -3
  37. package/dist/index.d.ts +2 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +4 -3
  40. package/dist/lib/ai/models.d.ts +6 -0
  41. package/dist/lib/ai/models.d.ts.map +1 -1
  42. package/dist/lib/types.d.ts +23 -0
  43. package/dist/lib/types.d.ts.map +1 -1
  44. package/dist/{models-DUt7W9lV.js → models-DphUIx22.js} +13 -2
  45. package/dist/pages/ChatNewPage.d.ts +6 -1
  46. package/dist/pages/ChatNewPage.d.ts.map +1 -1
  47. package/dist/pages/ChatPage.d.ts +6 -1
  48. package/dist/pages/ChatPage.d.ts.map +1 -1
  49. package/dist/routes.browser.js +1 -1
  50. package/dist/routes.js +1 -1
  51. package/dist/runtime.d.ts +2 -2
  52. package/dist/runtime.d.ts.map +1 -1
  53. package/dist/runtime.js +1 -1
  54. package/dist/tailwind-source.js +1 -1
  55. package/package.json +1 -1
@@ -2,7 +2,7 @@ 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 ee, x as g, y as _ } from "./chatDb-BSiHIyn9.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, x as _, y as ee } from "./chatDb-BSiHIyn9.js";
6
6
  import { n as v, t as y } from "./resumableSse-BprFOR5Q.js";
7
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";
@@ -13,53 +13,53 @@ import { openai as k } from "@ai-sdk/openai";
13
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/", ue = new Set([
16
+ var j = /-thinking$/, M = "openai/", N = "google/", P = "xai/", F = 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
- ]), de = (e) => e.startsWith(M), fe = (e) => e.startsWith(N), pe = (e) => e.startsWith(P), F = (e) => e.endsWith("-thinking"), I = le({
21
+ ]), ue = (e) => e.startsWith(M), de = (e) => e.startsWith(N), fe = (e) => e.startsWith(P), pe = (e) => e.endsWith("-thinking"), me = (e) => e.includes("/") ? ue(e) || de(e) || fe(e) : !1, I = le({
22
22
  baseURL: process.env.XAI_BASE_URL ?? "https://api.x.ai/v1",
23
23
  apiKey: process.env.XAI_API_KEY
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)) {
24
+ }), L = ce({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY }), he = (e) => {
25
+ if (ue(e)) return k.responses(e.slice(M.length));
26
+ if (de(e)) {
27
27
  let t = e.slice(N.length).replace(j, ""), n = L.chat(t);
28
- return F(e) ? w({
28
+ return pe(e) ? w({
29
29
  model: n,
30
30
  middleware: re({ tagName: "thinking" })
31
31
  }) : n;
32
32
  }
33
- if (pe(e)) {
33
+ if (fe(e)) {
34
34
  let t = e.slice(P.length).replace(j, "");
35
- return F(e) ? I.responses(t) : I.chat(t);
35
+ return pe(e) ? I.responses(t) : I.chat(t);
36
36
  }
37
37
  throw Error(`Unsupported modelId: ${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) => `\
38
+ }, ge = () => k.chat("gpt-5.4-mini"), R = () => k.chat(process.env.AGENT_SDK_ARTIFACT_MODEL ?? "gpt-5.4-mini"), z = "\nArtifacts is a special user interface mode that helps users with writing, editing, and other content creation tasks. When artifact is open, it is on the right side of the screen, while the conversation is on the left side. When creating, editing, or updating documents, changes are reflected in real-time on the artifacts and visible to the user.\n\nWhen asked to write code, always use artifacts. When writing code, specify the language in the backticks, e.g. ```python`code here```. The default language is Python. Other languages are not yet supported, so let the user know if they request a different language.\n\nCritical rules:\n- Only call one artifact tool per response.\n- Do not update or edit a document immediately after creating it. Wait for user feedback or an explicit request to modify it.\n- After creating, editing, or updating an artifact, do not repeat the full artifact content in chat. The user can already see it.\n\nThis is a guide for using artifacts tools: `createDocument`, `editDocument`, `updateDocument`, and `requestSuggestions`, which render content on artifacts beside the conversation.\n\n**When to use `createDocument`:**\n- For substantial content (>10 lines) or code\n- For content users will likely save/reuse (emails, code, essays, etc.)\n- When explicitly requested to create a document\n- For when content contains a single code snippet\n- Use kind \"code\" for programming, \"text\" for writing, and \"sheet\" for tabular/CSV data\n\n**When NOT to use `createDocument`:**\n- For informational/explanatory content\n- For conversational responses\n- When asked to keep it in chat\n\n**Using `editDocument`:**\n- Prefer this for targeted edits to an existing artifact\n- For scripts: fixing bugs, adding/removing lines, renaming variables, adding logs\n- For documents: fixing typos, rewording paragraphs, inserting or replacing sections\n- Provide an exact `old_string` and `new_string`\n- Include enough surrounding context in `old_string` to make the match unique\n- Use `replace_all: true` only for deliberate repeated replacements, like renaming a variable everywhere\n\n**Using `updateDocument`:**\n- Default to full document rewrites for major changes\n- Use `editDocument` instead for specific, isolated changes\n- Follow user instructions for which parts to modify\n\n**When NOT to use `editDocument` or `updateDocument`:**\n- Immediately after creating a document\n- Without an explicit user request to modify the artifact\n\n**Using `requestSuggestions`:**\n- ONLY use when the user explicitly asks for suggestions on an existing document\n- Requires a valid document ID from a previously created document\n- Never use for general questions or information requests\n", B = "You are a friendly assistant! Keep your responses concise and helpful.\n\nWhen asked to write, create, or help with something, just do it directly. Don't ask clarifying questions unless absolutely necessary - make reasonable assumptions and proceed with the task.", V = (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
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");
45
+ let i = V(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") ? `${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}`;
47
+ let t = e.startsWith("google/") && e.includes("thinking") ? `${B}\n\nWhen you reason, put your reasoning inside <thinking>...</thinking> tags. Then provide your final answer outside of those tags.\n\n${i}` : `${B}\n\n${i}`;
48
48
  return a ? `${t}\n\n${a}` : t;
49
49
  }
50
- let o = `${z}\n\n${i}\n\n${ge}`;
50
+ let o = `${B}\n\n${i}\n\n${z}`;
51
51
  return a ? `${o}\n\n${a}` : o;
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) => {
52
+ }, ve = "\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", ye = "\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", be = (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
- }, 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);
57
+ }, xe = "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", Se = 24, Ce = 8e4, we = 16e3, Te = "agent-runtime-history-compaction-summary", H = (e) => !!e && typeof e == "object" && !Array.isArray(e), U = (e) => typeof e == "string" && e.trim() ? e.trim() : null, Ee = (e) => {
58
+ let t = U((H(e.metadata) ? e.metadata : null)?.createdAt);
59
59
  if (!t) return null;
60
60
  let n = new Date(t);
61
61
  return Number.isNaN(n.getTime()) ? null : t;
62
- }, G = (e, t = 2e3) => {
62
+ }, W = (e, t = 2e3) => {
63
63
  if (typeof e == "string") return e.length > t ? `${e.slice(0, t)}...` : e;
64
64
  if (typeof e == "number" || typeof e == "boolean") return String(e);
65
65
  if (!e || typeof e != "object") return "";
@@ -69,52 +69,52 @@ ${e}`;
69
69
  } catch {
70
70
  return "[unserializable content]";
71
71
  }
72
- }, Te = (e) => (Array.isArray(e.parts) ? e.parts : []).flatMap((e) => {
73
- if (!U(e)) {
74
- let t = G(e);
72
+ }, De = (e) => (Array.isArray(e.parts) ? e.parts : []).flatMap((e) => {
73
+ if (!H(e)) {
74
+ let t = W(e);
75
75
  return t ? [t] : [];
76
76
  }
77
- let t = W(e.type) ?? "part", n = G(e.text);
77
+ let t = U(e.type) ?? "part", n = W(e.text);
78
78
  if (n) return [`${t}: ${n}`];
79
- let r = G(e.output);
79
+ let r = W(e.output);
80
80
  if (r) return [`${t}: ${r}`];
81
- let i = G(e.result);
81
+ let i = W(e.result);
82
82
  if (i) return [`${t}: ${i}`];
83
- let a = G(e.content);
83
+ let a = W(e.content);
84
84
  if (a) return [`${t}: ${a}`];
85
- let o = G(e, 1e3);
85
+ let o = W(e, 1e3);
86
86
  return o ? [`${t}: ${o}`] : [];
87
- }).join("\n").trim(), Ee = (e) => e.reduce((e, t) => e + Te(t).length, 0), De = (e, t) => {
87
+ }).join("\n").trim(), Oe = (e) => e.reduce((e, t) => e + De(t).length, 0), ke = (e, t) => {
88
88
  if (e.length <= t) return e;
89
89
  if (t <= 32) return e.slice(0, t);
90
90
  let n = Math.floor(t * .7), r = Math.max(0, t - n - 24);
91
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
92
+ }, Ae = (e) => e ? {
93
+ maxMessages: Number.isFinite(e.maxMessages) && Number(e.maxMessages) > 0 ? Math.floor(Number(e.maxMessages)) : Se,
94
+ maxEstimatedChars: Number.isFinite(e.maxEstimatedChars) && Number(e.maxEstimatedChars) > 0 ? Math.floor(Number(e.maxEstimatedChars)) : Ce,
95
+ maxSummaryChars: Number.isFinite(e.maxSummaryChars) && Number(e.maxSummaryChars) > 0 ? Math.floor(Number(e.maxSummaryChars)) : we
96
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) ? {
97
+ maxMessages: Se,
98
+ maxEstimatedChars: Ce,
99
+ maxSummaryChars: we
100
+ }, G = (e) => H(e) && e.type === "agent-runtime-history-compaction" && e.version === 1 && typeof e.summary == "string", je = (e) => G(e) ? e : H(e) && G(e.historyCompaction) ? e.historyCompaction : null, Me = (e, t) => t ? H(e) && !G(e) ? {
101
101
  ...e,
102
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) => {
103
+ } : { historyCompaction: t } : e ?? null, Ne = (e) => U(e.id), Pe = (e, t) => {
104
+ let n = U(t?.compactedThroughMessageId);
105
+ return n ? e.findIndex((e) => Ne(e) === n) : -1;
106
+ }, Fe = (e, t) => {
107
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;
108
+ for (; i < e.length - r && Oe(e.slice(i)) > t.maxEstimatedChars;) i += 1;
109
109
  return i;
110
- }, Pe = (e) => {
111
- let t = W(e.role) ?? "message", n = we(e), r = Te(e);
110
+ }, Ie = (e) => {
111
+ let t = U(e.role) ?? "message", n = Ee(e), r = De(e);
112
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"}`,
113
+ }, Le = ({ previousContext: e, messagesToCompact: t, limits: n }) => {
114
+ let r = e?.summary?.trim(), i = t.map(Ie).join("\n\n").trim();
115
+ return ke([r ? `Earlier summary:\n${r}` : null, i ? `Compacted transcript:\n${i}` : null].filter((e) => !!e).join("\n\n"), n.maxSummaryChars).trim();
116
+ }, Re = (e) => ({
117
+ id: `${Te}:${U(e.compactedThroughMessageId) ?? "unknown"}`,
118
118
  role: "user",
119
119
  parts: [{
120
120
  type: "text",
@@ -130,42 +130,42 @@ ${e}`;
130
130
  transient: !0,
131
131
  historyCompaction: !0
132
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),
133
+ }), K = (e, t) => t?.summary.trim() ? [Re(t), ...e] : e, ze = ({ messages: e, previousContext: t, limits: n }) => {
134
+ let r = Pe(e, t), i = r >= 0 ? e.slice(r + 1) : e;
135
+ if (!(i.length > n.maxMessages || Oe(i) > n.maxEstimatedChars)) return {
136
+ messages: K(i, t),
137
137
  context: t
138
138
  };
139
- let a = Ne(i, n);
139
+ let a = Fe(i, n);
140
140
  if (a <= 0) return {
141
- messages: q(i, t),
141
+ messages: K(i, t),
142
142
  context: t
143
143
  };
144
144
  let o = i.slice(0, a), s = i.slice(a), c = o.at(-1) ?? null, l = {
145
145
  type: "agent-runtime-history-compaction",
146
146
  version: 1,
147
- summary: Fe({
147
+ summary: Le({
148
148
  previousContext: t,
149
149
  messagesToCompact: o,
150
150
  limits: n
151
151
  }),
152
- compactedThroughMessageId: c ? je(c) : t?.compactedThroughMessageId ?? null,
153
- compactedThroughMessageCreatedAt: c ? we(c) : t?.compactedThroughMessageCreatedAt ?? null,
152
+ compactedThroughMessageId: c ? Ne(c) : t?.compactedThroughMessageId ?? null,
153
+ compactedThroughMessageCreatedAt: c ? Ee(c) : t?.compactedThroughMessageCreatedAt ?? null,
154
154
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
155
155
  messageCount: e.length
156
156
  };
157
157
  return {
158
- messages: q(s, l),
158
+ messages: K(s, l),
159
159
  context: l
160
160
  };
161
- }, Re = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a, messages: o, lastContext: s }) => {
161
+ }, Be = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a, messages: o, lastContext: s }) => {
162
162
  let c = r().historyCompaction;
163
163
  if (c === !1 || c && c.enabled === !1) return {
164
164
  messages: o,
165
165
  lastContext: s ?? null,
166
166
  lastContextChanged: !1
167
167
  };
168
- let l = Oe(c), u = ke(s);
168
+ let l = Ae(c), u = je(s);
169
169
  try {
170
170
  let r = typeof c == "object" && typeof c.compact == "function" ? await c.compact({
171
171
  ctx: e,
@@ -176,14 +176,14 @@ ${e}`;
176
176
  messages: o,
177
177
  previousContext: u,
178
178
  limits: l
179
- }) : Le({
179
+ }) : ze({
180
180
  messages: o,
181
181
  previousContext: u,
182
182
  limits: l
183
183
  }), d = Array.isArray(r.messages) ? r.messages : o, f = r.context === void 0 ? u : r.context;
184
184
  return {
185
185
  messages: d,
186
- lastContext: Ae(s, f ?? null),
186
+ lastContext: Me(s, f ?? null),
187
187
  lastContextChanged: f !== u
188
188
  };
189
189
  } catch (e) {
@@ -193,11 +193,11 @@ ${e}`;
193
193
  lastContextChanged: !1
194
194
  };
195
195
  }
196
- }, ze = [
196
+ }, q = [
197
197
  "text",
198
198
  "code",
199
199
  "sheet"
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 }) => {
200
+ ], Ve = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, J = () => !Ve(process.env.AGENT_SDK_LIVE_TOOLS) && (Ve(process.env.PLAYWRIGHT) || process.env.NODE_ENV === "test"), He = async ({ system: e, prompt: t, dataStream: n, providerOptions: r }) => {
201
201
  if (J()) {
202
202
  let e = `Stub document: ${t}`;
203
203
  return n.write({
@@ -219,7 +219,7 @@ ${e}`;
219
219
  transient: !0
220
220
  }));
221
221
  return i;
222
- }, He = async ({ system: e, prompt: t, dataStream: n }) => {
222
+ }, Ue = async ({ system: e, prompt: t, dataStream: n }) => {
223
223
  if (J()) {
224
224
  let e = `print("Stub code for: ${t}")\n`;
225
225
  return n.write({
@@ -244,7 +244,7 @@ ${e}`;
244
244
  }), r = t);
245
245
  }
246
246
  return r;
247
- }, Ue = async ({ system: e, prompt: t, dataStream: n }) => {
247
+ }, We = async ({ system: e, prompt: t, dataStream: n }) => {
248
248
  if (J()) {
249
249
  let e = `name,value\n${t.replaceAll(",", " ")},1\n`;
250
250
  return n.write({
@@ -273,7 +273,7 @@ ${e}`;
273
273
  data: r,
274
274
  transient: !0
275
275
  }), r;
276
- }, We = async (e) => {
276
+ }, Ge = async (e) => {
277
277
  try {
278
278
  let t = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(e)}&count=1&language=en&format=json`);
279
279
  if (!t.ok) return null;
@@ -287,7 +287,7 @@ ${e}`;
287
287
  } catch {
288
288
  return null;
289
289
  }
290
- }, Ge = ({ ctx: e, dataStream: t, requestHints: n }) => {
290
+ }, Ke = ({ ctx: e, dataStream: t, requestHints: n }) => {
291
291
  let r = i(e), a = async (t) => {
292
292
  let n = await h(e, t);
293
293
  return n.length > 0 ? n.at(-1) ?? null : null;
@@ -302,7 +302,7 @@ ${e}`;
302
302
  execute: async (e) => {
303
303
  let t, n;
304
304
  if (e.city) {
305
- let r = await We(e.city);
305
+ let r = await Ge(e.city);
306
306
  if (!r) return { error: `Could not find coordinates for "${e.city}". Please check the city name.` };
307
307
  t = r.latitude, n = r.longitude;
308
308
  } else if (e.latitude !== void 0 && e.longitude !== void 0) t = e.latitude, n = e.longitude;
@@ -314,7 +314,7 @@ ${e}`;
314
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.",
315
315
  inputSchema: A.object({
316
316
  title: A.string().describe("The title of the artifact"),
317
- kind: A.enum(ze).describe("Use 'code' for programming, 'text' for prose, and 'sheet' for CSV/tabular data")
317
+ kind: A.enum(q).describe("Use 'code' for programming, 'text' for prose, and 'sheet' for CSV/tabular data")
318
318
  }),
319
319
  execute: async ({ title: n, kind: r }) => {
320
320
  let i = D();
@@ -336,16 +336,16 @@ ${e}`;
336
336
  transient: !0
337
337
  });
338
338
  let a = "";
339
- return r === "text" ? a = await Ve({
339
+ return r === "text" ? a = await He({
340
340
  system: "Write about the given topic. Markdown is supported. Use headings wherever appropriate.",
341
341
  prompt: n,
342
342
  dataStream: t
343
- }) : r === "code" ? a = await He({
344
- system: V,
343
+ }) : r === "code" ? a = await Ue({
344
+ system: ve,
345
345
  prompt: n,
346
346
  dataStream: t
347
- }) : r === "sheet" && (a = await Ue({
348
- system: ve,
347
+ }) : r === "sheet" && (a = await We({
348
+ system: ye,
349
349
  prompt: n,
350
350
  dataStream: t
351
351
  })), await f(e, {
@@ -374,27 +374,27 @@ ${e}`;
374
374
  let i = await a(n);
375
375
  if (!i) return { error: "Document not found" };
376
376
  let o = i.kind;
377
- if (!ze.includes(o)) return { error: `Unsupported document kind: ${i.kind}` };
377
+ if (!q.includes(o)) return { error: `Unsupported document kind: ${i.kind}` };
378
378
  t.write({
379
379
  type: "data-clear",
380
380
  data: null,
381
381
  transient: !0
382
382
  });
383
383
  let s = "";
384
- return o === "text" ? s = await Ve({
385
- system: H(i.content, i.kind),
384
+ return o === "text" ? s = await He({
385
+ system: be(i.content, i.kind),
386
386
  prompt: r,
387
387
  dataStream: t,
388
388
  providerOptions: { openai: { prediction: {
389
389
  type: "content",
390
390
  content: i.content
391
391
  } } }
392
- }) : o === "code" ? s = await He({
393
- system: H(i.content, i.kind),
392
+ }) : o === "code" ? s = await Ue({
393
+ system: be(i.content, i.kind),
394
394
  prompt: r,
395
395
  dataStream: t
396
- }) : o === "sheet" && (s = await Ue({
397
- system: H(i.content, i.kind),
396
+ }) : o === "sheet" && (s = await We({
397
+ system: be(i.content, i.kind),
398
398
  prompt: r,
399
399
  dataStream: t
400
400
  })), await f(e, {
@@ -430,7 +430,7 @@ ${e}`;
430
430
  if (!s) return { error: "Document not found" };
431
431
  if (!s.content) return { error: "Document has no content" };
432
432
  let c = s.kind;
433
- if (!ze.includes(c)) return { error: `Unsupported document kind: ${s.kind}` };
433
+ if (!q.includes(c)) return { error: `Unsupported document kind: ${s.kind}` };
434
434
  if (!s.content.includes(r)) return { error: "old_string not found in document" };
435
435
  let l = o ? s.content.replaceAll(r, i) : s.content.replace(r, i);
436
436
  return await f(e, {
@@ -550,39 +550,48 @@ ${e}`;
550
550
  }
551
551
  })
552
552
  };
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) => {
553
+ }, qe = (e) => e ? !e.trim() : !0, Je = (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(), Ye = (e) => {
554
554
  let t = e.trim();
555
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;
556
- }, Ye = (e) => {
556
+ }, Xe = (e) => {
557
557
  let t = e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").replace(/\s+/g, " ").trim();
558
558
  return t === "hi" || t === "hello" || t === "hey" || t === "salut" || t === "bonjour";
559
559
  }, Y = (e) => {
560
560
  let t = e.trim();
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";
561
+ return !t || Xe(t) ? "" : Ye(t.replaceAll("\n", " ").replaceAll("\r", " ").split(/\s+/).filter((e) => e.trim() !== "").slice(0, 5).join(" "));
562
+ }, Ze = "/api/rb/agents/chat";
563
563
  A.any(), A.any();
564
564
  //#endregion
565
565
  //#region src/api/chat/handler.ts
566
- var Ze = /* @__PURE__ */ e({
567
- default: () => Lt,
566
+ var Qe = /* @__PURE__ */ e({
567
+ default: () => zt,
568
568
  runAgentLoop: () => $
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) => {
569
+ }), $e = 1024 * 1024 * 20, et = 1e5, tt = /^\/api\/rb\/files\/([^/]+)\/?$/, nt = "test-model", rt = "openai/gpt-5.4-mini", it = async (e) => new Promise((t) => setTimeout(t, e)), at = async (e, t) => {
570
570
  let n = v(t);
571
571
  n && !n.isDone || await c(e, {
572
572
  chatId: t,
573
573
  isStreaming: !1
574
574
  });
575
- }, at = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, X = (e) => typeof e == "string" && e.trim() || null, ot = (e) => {
575
+ }, ot = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, X = (e) => typeof e == "string" && e.trim() || null, st = () => {
576
+ let e = r().chatModels;
577
+ if (!e?.length) return F;
578
+ let t = /* @__PURE__ */ new Set();
579
+ for (let n of e) {
580
+ let e = X(typeof n == "string" ? n : n.id);
581
+ e && t.add(e);
582
+ }
583
+ return t;
584
+ }, ct = (e) => {
576
585
  if (typeof e == "boolean") return e;
577
586
  let t = X(e)?.toLowerCase();
578
587
  return t ? t === "true" ? !0 : t === "false" ? !1 : null : null;
579
- }, st = (e) => {
588
+ }, lt = (e) => {
580
589
  let t = e.req?.session?.user?.currentTenantId;
581
590
  return X(t);
582
- }, ct = (e) => {
591
+ }, ut = (e) => {
583
592
  let t = e.req?.session?.user?.id;
584
593
  return X(t);
585
- }, lt = () => X(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", ut = (e) => E("sha256").update(Buffer.from(e)).digest("hex"), dt = (e) => {
594
+ }, dt = () => X(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", ft = (e) => E("sha256").update(Buffer.from(e)).digest("hex"), pt = (e) => {
586
595
  let t = e.trim();
587
596
  if (!t) return null;
588
597
  let n;
@@ -595,15 +604,15 @@ var Ze = /* @__PURE__ */ e({
595
604
  return null;
596
605
  }
597
606
  }
598
- let r = et.exec(n.pathname);
607
+ let r = tt.exec(n.pathname);
599
608
  if (!r) return null;
600
609
  let i = X(decodeURIComponent(r[1]));
601
610
  return i ? {
602
611
  fileId: i,
603
612
  uploadKey: X(n.searchParams.get("rb-upload-key"))
604
613
  } : null;
605
- }, ft = async ({ ctx: e, fileId: t, uploadKey: n }) => {
606
- let r = st(e);
614
+ }, mt = async ({ ctx: e, fileId: t, uploadKey: n }) => {
615
+ let r = lt(e);
607
616
  if (!r) throw Error("tenant_missing");
608
617
  let i;
609
618
  try {
@@ -613,18 +622,18 @@ var Ze = /* @__PURE__ */ e({
613
622
  }
614
623
  let a = (await T(r)).db;
615
624
  if (!a) throw Error("filesystem_db_unavailable");
616
- let o = new se(a, { bucketName: lt() }), [s] = await o.find({ _id: i }).limit(1).toArray();
625
+ let o = new se(a, { bucketName: dt() }), [s] = await o.find({ _id: i }).limit(1).toArray();
617
626
  if (!s) throw Error("file_not_found");
618
- let c = ot(s?.metadata?.isPublic) ?? !1, l = ct(e), u = X(s?.metadata?.userId), d = X(s?.metadata?.ownerKeyHash);
627
+ let c = ct(s?.metadata?.isPublic) ?? !1, l = ut(e), u = X(s?.metadata?.userId), d = X(s?.metadata?.ownerKeyHash);
619
628
  if (!c) {
620
- let e = !!(l && u && l === u), t = !!(n && d && ut(n) === d);
629
+ let e = !!(l && u && l === u), t = !!(n && d && ft(n) === d);
621
630
  if (!e && !t) throw Error("unauthorized");
622
631
  }
623
632
  let f = X(s?.metadata?.mimeType), p = [], m = 0;
624
633
  return await new Promise((e, t) => {
625
634
  let n = o.openDownloadStream(i);
626
635
  n.on("data", (e) => {
627
- if (m += e.length, m > Qe) {
636
+ if (m += e.length, m > $e) {
628
637
  n.destroy(/* @__PURE__ */ Error("attachment_too_large"));
629
638
  return;
630
639
  }
@@ -634,16 +643,16 @@ var Ze = /* @__PURE__ */ e({
634
643
  data: Buffer.concat(p, m),
635
644
  mimeType: f
636
645
  };
637
- }, pt = async (e, t) => {
646
+ }, ht = async (e, t) => {
638
647
  let n = Array.isArray(t) ? t : [], r = [];
639
648
  for (let t of n) {
640
649
  if (!t || typeof t != "object" || !("role" in t) || t.role !== "user") continue;
641
650
  let n = Array.isArray(t.content) ? t.content : null;
642
651
  if (n) for (let t of n) {
643
652
  if (!t || typeof t != "object" || t.type !== "file" || typeof t.data != "string") continue;
644
- let n = dt(t.data);
653
+ let n = pt(t.data);
645
654
  n && r.push((async () => {
646
- let { data: r, mimeType: i } = await ft({
655
+ let { data: r, mimeType: i } = await mt({
647
656
  ctx: e,
648
657
  ...n
649
658
  });
@@ -652,7 +661,7 @@ var Ze = /* @__PURE__ */ e({
652
661
  }
653
662
  }
654
663
  r.length > 0 && await Promise.all(r);
655
- }, mt = (e) => {
664
+ }, gt = (e) => {
656
665
  let t = Array.isArray(e) ? e : [];
657
666
  for (let e of t) {
658
667
  if (!e || typeof e != "object" || !("role" in e) || e.role !== "user") continue;
@@ -665,7 +674,7 @@ var Ze = /* @__PURE__ */ e({
665
674
  let i = X(n.filename) ?? X(n.name) ?? `attachment-${e + 1}`, a = n.data;
666
675
  if (r?.startsWith("text/") && a instanceof Uint8Array) {
667
676
  let n = (Buffer.isBuffer(a) ? a : Buffer.from(a)).toString("utf8");
668
- n.length > $e && (n = `${n.slice(0, $e)}\n\n[Truncated]`);
677
+ n.length > et && (n = `${n.slice(0, et)}\n\n[Truncated]`);
669
678
  let o = r === "text/csv" || i.toLowerCase().endsWith(".csv") ? "csv" : "";
670
679
  t[e] = {
671
680
  type: "text",
@@ -680,14 +689,14 @@ var Ze = /* @__PURE__ */ e({
680
689
  };
681
690
  }
682
691
  }
683
- }, ht = async (e, t, n) => {
684
- if (e.message?.role === "user") return qe(e.message.parts);
692
+ }, _t = async (e, t, n) => {
693
+ if (e.message?.role === "user") return Je(e.message.parts);
685
694
  if (Array.isArray(e.messages)) {
686
695
  let t = null;
687
696
  for (let n = e.messages.length - 1; n >= 0; --n) {
688
697
  let r = e.messages[n];
689
698
  if (r?.role !== "user") continue;
690
- let i = qe(r.parts);
699
+ let i = Je(r.parts);
691
700
  if (i) {
692
701
  if (Y(i)) return i;
693
702
  t ??= i;
@@ -699,40 +708,40 @@ var Ze = /* @__PURE__ */ e({
699
708
  for (let e = r.length - 1; e >= 0; --e) {
700
709
  let t = r[e];
701
710
  if (t.role !== "user") continue;
702
- let n = qe(t.parts);
711
+ let n = Je(t.parts);
703
712
  if (n) {
704
713
  if (Y(n)) return n;
705
714
  i ??= n;
706
715
  }
707
716
  }
708
717
  return i ?? "";
709
- }, gt = (e) => {
718
+ }, vt = (e) => {
710
719
  let t = Array.isArray(e.messages) && e.messages.length > 0 ? e.messages.at(-1) : e.message;
711
720
  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();
712
- }, _t = (e) => {
721
+ }, yt = (e) => {
713
722
  let t = e.id;
714
723
  return typeof t == "string" && t.trim() !== "" ? t : null;
715
- }, vt = (e) => {
724
+ }, bt = (e) => {
716
725
  let t = e.selectedChatModel;
717
726
  return typeof t == "string" && t.trim() !== "" ? t : null;
718
- }, yt = (e) => {
727
+ }, xt = (e) => {
719
728
  let t = e.openaiReasoningEffort;
720
729
  return typeof t == "string" && t.trim() !== "" ? t.trim() : null;
721
- }, bt = (e) => {
730
+ }, St = (e) => {
722
731
  if (!e || typeof e != "object") return !1;
723
732
  let t = e.state, n = e.toolCallId;
724
733
  return typeof n == "string" && n.trim() !== "" && (t === "approval-responded" || t === "output-denied");
725
- }, xt = (e) => {
734
+ }, Ct = (e) => {
726
735
  let t = Array.isArray(e.messages) ? e.messages : [];
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) => {
736
+ return t.length === 0 || t.at(-1)?.role === "user" ? !1 : t.some((e) => (Array.isArray(e?.parts) ? e.parts : []).some((e) => St(e)));
737
+ }, wt = (e) => {
729
738
  let t = /* @__PURE__ */ new Map();
730
739
  for (let n of e) {
731
740
  let e = Array.isArray(n?.parts) ? n.parts : [];
732
- for (let n of e) bt(n) && t.set(n.toolCallId, n);
741
+ for (let n of e) St(n) && t.set(n.toolCallId, n);
733
742
  }
734
743
  return t;
735
- }, Ct = (e, t) => {
744
+ }, Tt = (e, t) => {
736
745
  let n = [];
737
746
  return {
738
747
  changedMessages: n,
@@ -755,21 +764,21 @@ var Ze = /* @__PURE__ */ e({
755
764
  return n.push(a), a;
756
765
  })
757
766
  };
758
- }, wt = (e) => {
767
+ }, Et = (e) => {
759
768
  if (!e || typeof e != "object" || !("createdAt" in e)) return null;
760
769
  let t = e.createdAt;
761
770
  if (typeof t != "string") return null;
762
771
  let n = new Date(t);
763
772
  return Number.isNaN(n.getTime()) ? null : n;
764
- }, Tt = (e) => ({
773
+ }, Dt = (e) => ({
765
774
  latitude: null,
766
775
  longitude: null,
767
776
  city: null,
768
777
  country: null
769
- }), Et = (e) => {
778
+ }), Ot = (e) => {
770
779
  let [t] = e.split("/");
771
780
  return t && t !== e ? t : "unknown";
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) => {
781
+ }, Z = (e) => typeof e == "number" && Number.isFinite(e) ? e : void 0, kt = (e) => e instanceof Error && e.message.trim() ? e.message : "Unknown error", At = (e) => {
773
782
  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 : {};
774
783
  return {
775
784
  inputTokens: Z(t.inputTokens),
@@ -779,13 +788,13 @@ var Ze = /* @__PURE__ */ e({
779
788
  reasoningTokens: Z(r.reasoningTokens) ?? Z(t.reasoningTokens),
780
789
  rawUsage: Object.keys(t).length > 0 ? t.raw ?? t : void 0
781
790
  };
782
- }, kt = () => ({
791
+ }, jt = () => ({
783
792
  inputTokens: 0,
784
793
  outputTokens: 0,
785
794
  totalTokens: 0,
786
795
  cachedInputTokens: 0,
787
796
  reasoningTokens: 0
788
- }), At = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a }) => {
797
+ }), Mt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: i, mode: a }) => {
789
798
  try {
790
799
  return { workspaceId: X((await r().resolveUsageContext?.({
791
800
  ctx: e,
@@ -798,35 +807,35 @@ var Ze = /* @__PURE__ */ e({
798
807
  return console.warn("Failed to resolve agent usage context.", e), { workspaceId: void 0 };
799
808
  }
800
809
  }, 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() }) => {
801
- let h = u ? Ot(u) : {}, ee = {
810
+ let h = u ? At(u) : {}, g = {
802
811
  id: D(),
803
812
  workspaceId: t.workspaceId,
804
813
  agentId: n.id,
805
814
  chatId: r,
806
815
  mode: i,
807
816
  feature: a,
808
- provider: Et(s),
817
+ provider: Ot(s),
809
818
  model: s,
810
819
  billable: l,
811
820
  status: c,
812
821
  finishReason: X(d) ?? void 0,
813
- errorMessage: f ? Dt(f) : void 0,
822
+ errorMessage: f ? kt(f) : void 0,
814
823
  ...h,
815
824
  startedAt: p,
816
825
  finishedAt: m,
817
826
  createdAt: /* @__PURE__ */ new Date()
818
827
  };
819
828
  try {
820
- await o(e, ee);
829
+ await o(e, g);
821
830
  } catch (e) {
822
831
  console.error("Failed to save agents usage event.", e);
823
832
  }
824
- }, jt = (e) => `agents-sdk:chat:${e}:stream`, Mt = async ({ ctx: e, chatId: t, selectedChatModel: i }) => await r().resolveAgent?.({
833
+ }, Nt = (e) => `agents-sdk:chat:${e}:stream`, Pt = async ({ ctx: e, chatId: t, selectedChatModel: i }) => await r().resolveAgent?.({
825
834
  ctx: e,
826
835
  chatId: t,
827
836
  selectedChatModel: i
828
- }) ?? n(), Nt = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
829
- let a = i(e), o = jt(t), s = y({
837
+ }) ?? n(), Ft = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
838
+ let a = i(e), o = Nt(t), s = y({
830
839
  chatId: t,
831
840
  abortWhenNoSubscribersMs: n === "headless" || r ? 0 : void 0
832
841
  });
@@ -854,31 +863,31 @@ var Ze = /* @__PURE__ */ e({
854
863
  });
855
864
  }
856
865
  };
857
- }, Pt = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
866
+ }, It = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
858
867
  if (!n) return;
859
868
  let a = i(e);
860
869
  n.publish({
861
870
  tenantId: a.tenantId,
862
871
  userId: a.userId,
863
- channel: jt(t),
872
+ channel: Nt(t),
864
873
  payload: {
865
874
  chatId: t,
866
875
  message: r
867
876
  }
868
877
  });
869
878
  }, $ = async ({ payload: e, ctx: n, mode: o = "interactive", streamTransport: l = null }) => {
870
- let f = _t(e);
879
+ let f = yt(e);
871
880
  if (!f) return a(n, "bad_request:api", "Parameter id is required.");
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";
881
+ let p = e, h = bt(p), v = ot(process.env.PLAYWRIGHT), y = !ot(process.env.AGENT_SDK_LIVE_CHAT) && v || process.env.NODE_ENV === "test";
873
882
  if (!h) return a(n, "bad_request:api", "Parameter selectedChatModel is required.");
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);
883
+ if (h === nt && (y = !0), h !== nt && (!st().has(h) || !me(h))) return a(n, "bad_request:api", `Unsupported selectedChatModel: "${h}".`);
884
+ 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 = ue(h), C = de(h), w = fe(h), T = xt(p), E = T && T !== "default" && T !== "off" ? T : null, se = t(h);
876
885
  if (E && !se.some((e) => e === E)) return a(n, "bad_request:api", `Unsupported reasoning effort "${E}" for selectedChatModel: "${h}".`);
877
886
  if (!y && x && !b) return a(n, "bad_request:provider", "Missing OPENAI_API_KEY.");
878
887
  if (!y && C && !re) return a(n, "bad_request:provider", "Missing GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY).");
879
888
  if (!y && w && !ae) return a(n, "bad_request:provider", "Missing XAI_API_KEY.");
880
889
  if (!y && !x && !C && !w) return a(n, "bad_request:provider", `Unsupported selectedChatModel: "${h}".`);
881
- let O = await Mt({
890
+ let O = await Pt({
882
891
  ctx: n,
883
892
  chatId: f,
884
893
  selectedChatModel: h
@@ -887,7 +896,7 @@ var Ze = /* @__PURE__ */ e({
887
896
  chatId: f,
888
897
  agent: O,
889
898
  selectedChatModel: h
890
- }) ?? null, k = await At({
899
+ }) ?? null, k = await Mt({
891
900
  ctx: n,
892
901
  chatId: f,
893
902
  agent: O,
@@ -895,7 +904,7 @@ var Ze = /* @__PURE__ */ e({
895
904
  mode: o
896
905
  }), le = i(n), A = await s(n, f, { includeDeleted: !0 });
897
906
  if (A?.deletedAt) return a(n, "not_found:chat");
898
- A ? A.selectedChatModel !== h && await _(n, {
907
+ A ? A.selectedChatModel !== h && await ee(n, {
899
908
  chatId: f,
900
909
  selectedChatModel: h
901
910
  }) : await m(n, {
@@ -917,7 +926,7 @@ var Ze = /* @__PURE__ */ e({
917
926
  parts: N,
918
927
  attachments: [],
919
928
  createdAt: e
920
- }]), Pt({
929
+ }]), It({
921
930
  ctx: n,
922
931
  chatId: f,
923
932
  streamTransport: l,
@@ -934,15 +943,15 @@ var Ze = /* @__PURE__ */ e({
934
943
  chatId: f,
935
944
  isStreaming: !0
936
945
  });
937
- let e = Nt({
946
+ let e = Ft({
938
947
  ctx: n,
939
948
  chatId: f,
940
949
  mode: o,
941
950
  streamTransport: l
942
951
  });
943
952
  try {
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, {
953
+ let t = Y(await _t(p, n, f)), r = await s(n, f);
954
+ r && qe(r.title) && t && t !== r.title && (await _(n, {
946
955
  chatId: f,
947
956
  title: t
948
957
  }), e.publishJson({
@@ -951,7 +960,7 @@ var Ze = /* @__PURE__ */ e({
951
960
  transient: !0
952
961
  }));
953
962
  let i = D();
954
- v && !e.abortController.signal.aborted && await rt(600), e.publishJson({
963
+ v && !e.abortController.signal.aborted && await it(600), e.publishJson({
955
964
  type: "start",
956
965
  messageId: i
957
966
  });
@@ -960,18 +969,18 @@ var Ze = /* @__PURE__ */ e({
960
969
  type: "text-start",
961
970
  id: a
962
971
  });
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);
972
+ let c = vt(p), l = c ? `Echo: ${c}` : "Hello from agents-sdk", d = Date.now(), m = l.split(/(\s+)/).filter((e) => e.length > 0);
964
973
  for (let t of m) {
965
974
  if (e.abortController.signal.aborted) break;
966
975
  e.publishJson({
967
976
  type: "text-delta",
968
977
  id: a,
969
978
  delta: t
970
- }), await rt(v ? 120 : 80);
979
+ }), await it(v ? 120 : 80);
971
980
  }
972
981
  if (v && !e.abortController.signal.aborted) {
973
982
  let e = Date.now() - d, t = 1200;
974
- e < t && await rt(t - e);
983
+ e < t && await it(t - e);
975
984
  }
976
985
  return e.abortController.signal.aborted ? {} : (e.publishJson({
977
986
  type: "text-end",
@@ -999,16 +1008,16 @@ var Ze = /* @__PURE__ */ e({
999
1008
  modelId: h,
1000
1009
  status: "success",
1001
1010
  billable: !1,
1002
- usage: kt(),
1011
+ usage: jt(),
1003
1012
  finishReason: "stop",
1004
1013
  startedAt: new Date(d)
1005
1014
  }), {});
1006
1015
  } finally {
1007
- await it(n, f);
1016
+ await at(n, f);
1008
1017
  }
1009
1018
  }
1010
- let P = Tt(n), I = xt(p);
1011
- if (Array.isArray(p.messages) && !I) {
1019
+ let P = Dt(n), F = Ct(p);
1020
+ if (Array.isArray(p.messages) && !F) {
1012
1021
  let e = p.messages.flatMap((e) => {
1013
1022
  let t = typeof e?.id == "string" ? e.id : null, n = typeof e?.role == "string" ? e.role : null, r = Array.isArray(e?.parts) ? e.parts : [];
1014
1023
  return !t || !n ? [] : [{
@@ -1017,66 +1026,66 @@ var Ze = /* @__PURE__ */ e({
1017
1026
  role: n,
1018
1027
  parts: r,
1019
1028
  attachments: [],
1020
- createdAt: wt(e?.metadata) ?? /* @__PURE__ */ new Date()
1029
+ createdAt: Et(e?.metadata) ?? /* @__PURE__ */ new Date()
1021
1030
  }];
1022
1031
  });
1023
1032
  e.length > 0 && await u(n, e);
1024
1033
  }
1025
- let L;
1026
- if (Array.isArray(p.messages) && p.messages.length > 0 && I) {
1034
+ let I;
1035
+ if (Array.isArray(p.messages) && p.messages.length > 0 && F) {
1027
1036
  let e = await d(n, f);
1028
- if (e.length === 0) L = p.messages;
1037
+ if (e.length === 0) I = p.messages;
1029
1038
  else {
1030
- let { changedMessages: t, updatedMessages: r } = Ct(e, St(p.messages));
1031
- t.length > 0 && await u(n, t), L = r.map((e) => ({
1039
+ let { changedMessages: t, updatedMessages: r } = Tt(e, wt(p.messages));
1040
+ t.length > 0 && await u(n, t), I = r.map((e) => ({
1032
1041
  id: e.id,
1033
1042
  role: e.role,
1034
1043
  parts: e.parts,
1035
1044
  metadata: { createdAt: e.createdAt.toISOString() }
1036
1045
  }));
1037
1046
  }
1038
- } else L = Array.isArray(p.messages) && p.messages.length > 0 ? p.messages : (await d(n, f)).map((e) => ({
1047
+ } else I = Array.isArray(p.messages) && p.messages.length > 0 ? p.messages : (await d(n, f)).map((e) => ({
1039
1048
  id: e.id,
1040
1049
  role: e.role,
1041
1050
  parts: e.parts,
1042
1051
  metadata: { createdAt: e.createdAt.toISOString() }
1043
1052
  }));
1044
- let R = I ? {
1045
- messages: L,
1053
+ let L = F ? {
1054
+ messages: I,
1046
1055
  lastContext: A?.lastContext ?? null,
1047
1056
  lastContextChanged: !1
1048
- } : await Re({
1057
+ } : await Be({
1049
1058
  ctx: n,
1050
1059
  chatId: f,
1051
1060
  agent: O,
1052
1061
  selectedChatModel: h,
1053
1062
  mode: o,
1054
- messages: L,
1063
+ messages: I,
1055
1064
  lastContext: A?.lastContext ?? null
1056
1065
  });
1057
- if (!I && R.lastContextChanged) try {
1058
- await ee(n, {
1066
+ if (!F && L.lastContextChanged) try {
1067
+ await g(n, {
1059
1068
  chatId: f,
1060
- lastContext: R.lastContext
1069
+ lastContext: L.lastContext
1061
1070
  });
1062
1071
  } catch (e) {
1063
1072
  console.warn("Failed to save compacted agent chat history context.", e);
1064
1073
  }
1065
- let ge = R.messages;
1074
+ let R = L.messages;
1066
1075
  await c(n, {
1067
1076
  chatId: f,
1068
1077
  isStreaming: !0
1069
1078
  });
1070
- let z = Nt({
1079
+ let z = Ft({
1071
1080
  ctx: n,
1072
1081
  chatId: f,
1073
1082
  mode: o,
1074
1083
  streamTransport: l
1075
1084
  }), B = "", V = "";
1076
1085
  try {
1077
- B = await ht(p, n, f), V = Y(B);
1086
+ B = await _t(p, n, f), V = Y(B);
1078
1087
  let e = await s(n, f);
1079
- e && Ke(e.title) && V && V !== e.title && (await g(n, {
1088
+ e && qe(e.title) && V && V !== e.title && (await _(n, {
1080
1089
  chatId: f,
1081
1090
  title: V
1082
1091
  }), z.publishJson({
@@ -1090,7 +1099,7 @@ var Ze = /* @__PURE__ */ e({
1090
1099
  errorText: "Something went wrong."
1091
1100
  }), z.publishDone();
1092
1101
  try {
1093
- await it(n, f);
1102
+ await at(n, f);
1094
1103
  } catch (e) {
1095
1104
  console.error("Failed to update chat streaming state.", e);
1096
1105
  }
@@ -1100,8 +1109,8 @@ var Ze = /* @__PURE__ */ e({
1100
1109
  let e = /* @__PURE__ */ new Date();
1101
1110
  try {
1102
1111
  let { text: t } = await ie({
1103
- model: he(),
1104
- system: ye,
1112
+ model: ge(),
1113
+ system: xe,
1105
1114
  prompt: B,
1106
1115
  onFinish: async (t) => {
1107
1116
  await Q({
@@ -1111,7 +1120,7 @@ var Ze = /* @__PURE__ */ e({
1111
1120
  chatId: f,
1112
1121
  mode: o,
1113
1122
  feature: "title",
1114
- modelId: nt,
1123
+ modelId: rt,
1115
1124
  status: "success",
1116
1125
  billable: !0,
1117
1126
  usage: t.totalUsage ?? t.usage,
@@ -1119,11 +1128,11 @@ var Ze = /* @__PURE__ */ e({
1119
1128
  startedAt: e
1120
1129
  });
1121
1130
  }
1122
- }), r = Je(t);
1131
+ }), r = Ye(t);
1123
1132
  if (!r) return;
1124
1133
  let i = await s(n, f);
1125
1134
  if (!i) return;
1126
- i.title !== r && (await g(n, {
1135
+ i.title !== r && (await _(n, {
1127
1136
  chatId: f,
1128
1137
  title: r
1129
1138
  }), z.publishJson({
@@ -1139,7 +1148,7 @@ var Ze = /* @__PURE__ */ e({
1139
1148
  chatId: f,
1140
1149
  mode: o,
1141
1150
  feature: "title",
1142
- modelId: nt,
1151
+ modelId: rt,
1143
1152
  status: "error",
1144
1153
  billable: !1,
1145
1154
  error: t,
@@ -1148,7 +1157,7 @@ var Ze = /* @__PURE__ */ e({
1148
1157
  }
1149
1158
  })();
1150
1159
  let ve = ne({
1151
- originalMessages: L,
1160
+ originalMessages: I,
1152
1161
  onError: (e) => (console.error(e), "Something went wrong."),
1153
1162
  onFinish: async ({ responseMessage: e }) => {
1154
1163
  let t = Array.isArray(e.parts) ? e.parts : [];
@@ -1162,7 +1171,7 @@ var Ze = /* @__PURE__ */ e({
1162
1171
  }]);
1163
1172
  },
1164
1173
  execute: async ({ writer: e }) => {
1165
- let t = Ge({
1174
+ let t = Ke({
1166
1175
  ctx: n,
1167
1176
  dataStream: e,
1168
1177
  requestHints: P
@@ -1179,7 +1188,7 @@ var Ze = /* @__PURE__ */ e({
1179
1188
  "editDocument",
1180
1189
  "updateDocument",
1181
1190
  "requestSuggestions"
1182
- ], s = F(h), c = s ? [] : x ? i : a, l = t, u = c, d = await r().resolveTools?.({
1191
+ ], s = pe(h), c = s ? [] : x ? i : a, l = t, u = c, d = await r().resolveTools?.({
1183
1192
  ctx: n,
1184
1193
  dataStream: e,
1185
1194
  requestHints: P,
@@ -1189,7 +1198,7 @@ var Ze = /* @__PURE__ */ e({
1189
1198
  defaultActiveTools: c
1190
1199
  });
1191
1200
  d && (l = d.tools, u = d.activeTools ?? Object.keys(d.tools));
1192
- let m = await te(ge.map((e) => ({
1201
+ let m = await te(R.map((e) => ({
1193
1202
  role: e?.role,
1194
1203
  parts: e?.parts,
1195
1204
  metadata: e?.metadata
@@ -1197,14 +1206,14 @@ var Ze = /* @__PURE__ */ e({
1197
1206
  tools: l,
1198
1207
  ignoreIncompleteToolCalls: !0
1199
1208
  });
1200
- await pt(n, m), x && mt(m);
1201
- let ee = typeof p.openaiReasoningSummary == "string" ? p.openaiReasoningSummary : null, g;
1202
- x && E ? g = { openai: {
1209
+ await ht(n, m), x && gt(m);
1210
+ let g = typeof p.openaiReasoningSummary == "string" ? p.openaiReasoningSummary : null, _;
1211
+ x && E ? _ = { openai: {
1203
1212
  reasoningEffort: E,
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({
1213
+ reasoningSummary: g ?? void 0
1214
+ } } : w && s && E && (_ = { xai: { reasoningEffort: E } });
1215
+ let ee = !1, v = /* @__PURE__ */ new Date(), y = async ({ status: e, usage: t, finishReason: r, error: i }) => {
1216
+ ee || (ee = !0, await Q({
1208
1217
  ctx: n,
1209
1218
  usageContext: k,
1210
1219
  agent: O,
@@ -1220,7 +1229,7 @@ var Ze = /* @__PURE__ */ e({
1220
1229
  startedAt: v
1221
1230
  }));
1222
1231
  }, b = S({
1223
- model: me(h),
1232
+ model: he(h),
1224
1233
  system: _e({
1225
1234
  selectedChatModel: h,
1226
1235
  requestHints: P,
@@ -1231,7 +1240,7 @@ var Ze = /* @__PURE__ */ e({
1231
1240
  tools: l,
1232
1241
  stopWhen: oe(5),
1233
1242
  abortSignal: z.abortController.signal,
1234
- providerOptions: g,
1243
+ providerOptions: _,
1235
1244
  activeTools: u,
1236
1245
  onFinish: async (e) => {
1237
1246
  await y({
@@ -1255,7 +1264,7 @@ var Ze = /* @__PURE__ */ e({
1255
1264
  }
1256
1265
  });
1257
1266
  e.merge(b.toUIMessageStream({
1258
- originalMessages: L,
1267
+ originalMessages: I,
1259
1268
  sendReasoning: s || !!(x && E)
1260
1269
  }));
1261
1270
  }
@@ -1278,24 +1287,24 @@ var Ze = /* @__PURE__ */ e({
1278
1287
  } finally {
1279
1288
  e?.();
1280
1289
  try {
1281
- await it(n, f);
1290
+ await at(n, f);
1282
1291
  } catch (e) {
1283
1292
  console.error("Failed to update chat streaming state.", e);
1284
1293
  }
1285
1294
  }
1286
1295
  })(), {};
1287
- }, Ft = async (e, t) => $({
1296
+ }, Lt = async (e, t) => $({
1288
1297
  payload: e,
1289
1298
  ctx: t,
1290
1299
  mode: "interactive"
1291
- }), It = async (e, t) => {
1300
+ }), Rt = async (e, t) => {
1292
1301
  let n = t.req.query.id, r = Array.isArray(n) ? n[0] : n;
1293
1302
  return typeof r != "string" || r.trim() === "" ? a(t, "bad_request:api") : p(t, r);
1294
- }, Lt = (e) => {
1295
- e.get(Xe, (async (e, t) => {
1303
+ }, zt = (e) => {
1304
+ e.get(Ze, (async (e, t) => {
1296
1305
  let n = t.req.query.id, r = Array.isArray(n) ? n[0] : n;
1297
1306
  return typeof r != "string" || r.trim() === "" ? a(t, "bad_request:api", "Parameter id is required.") : await s(t, r) || a(t, "not_found:chat");
1298
- })), e.post(Xe, Ft), e.delete(Xe, It);
1307
+ })), e.post(Ze, Lt), e.delete(Ze, Rt);
1299
1308
  };
1300
1309
  //#endregion
1301
- export { $ as n, Ze as t };
1310
+ export { $ as n, Qe as t };