@rpcbase/agents-sdk 0.12.0 → 0.14.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.
- package/dist/agents-sdk.css +1 -1
- package/dist/api/chat/handler.d.ts.map +1 -1
- package/dist/api/chat/models.d.ts +2 -2
- package/dist/api/chat/models.d.ts.map +1 -1
- package/dist/api/chat/runtimeConfig.d.ts +80 -0
- package/dist/api/chat/runtimeConfig.d.ts.map +1 -1
- package/dist/api/chat/toolApproval.d.ts +36 -0
- package/dist/api/chat/toolApproval.d.ts.map +1 -0
- package/dist/api/chat/toolApprovalHistory.d.ts +4 -0
- package/dist/api/chat/toolApprovalHistory.d.ts.map +1 -0
- package/dist/api/chatDb.d.ts +6 -1
- package/dist/api/chatDb.d.ts.map +1 -1
- package/dist/api/chatStore.d.ts +5 -0
- package/dist/api/chatStore.d.ts.map +1 -1
- package/dist/chat-models.browser.js +1 -1
- package/dist/chat-models.js +1 -1
- package/dist/{chatDb-CJCdqpjR.js → chatDb-DTjvCb7r.js} +33 -21
- package/dist/{chatDb-DLQOzat8.js → chatDb-DwhaaOmO.js} +33 -21
- package/dist/client-routes.browser.js +2 -2
- package/dist/client-routes.js +2 -2
- package/dist/components/ai-elements/tool.d.ts +6 -2
- package/dist/components/ai-elements/tool.d.ts.map +1 -1
- package/dist/components/message.d.ts.map +1 -1
- package/dist/{data-stream-handler-83PApswO.js → data-stream-handler-CrwpY1gX.js} +918 -813
- package/dist/{data-stream-handler-Cm6JVGl8.js → data-stream-handler-DG3Y--2n.js} +918 -813
- package/dist/{handler-C-CFaSnD.js → handler-0bIpqvbt.js} +1 -1
- package/dist/{handler-BTWWHJUs.js → handler-B-erVnQ6.js} +1 -1
- package/dist/handler-B4jvOK-L.js +1913 -0
- package/dist/{handler-D88wEmsv.js → handler-BLKbyYqI.js} +1 -1
- package/dist/{handler-BMF6eWg5.js → handler-BnDd10G3.js} +1 -1
- package/dist/{handler-DnkxwQzf.js → handler-Bsto5ImB.js} +1 -1
- package/dist/{handler-Cl7-HRxy.js → handler-By4I5hjo.js} +9 -9
- package/dist/{handler-C34eWXJg.js → handler-C3GOpsFS.js} +1 -1
- package/dist/{handler-DilZY3o3.js → handler-CNnPLVlT.js} +1 -1
- package/dist/{handler-DOtL2C2i.js → handler-CsNuMrRb.js} +1 -1
- package/dist/{handler-DiyNUz4m.js → handler-DAcB4fHJ.js} +1 -1
- package/dist/{handler-D003Oipd.js → handler-DUljRc5z.js} +1 -1
- package/dist/handler-DgrIym9_.js +1907 -0
- package/dist/{handler-CG2GBD33.js → handler-DtSnDhW2.js} +1 -1
- package/dist/{handler-DBuF7L41.js → handler-RTP9W4lT.js} +9 -9
- package/dist/{handler-CwoR5Bdv.js → handler-hTPifowr.js} +1 -1
- package/dist/index.browser.js +2 -2
- package/dist/index.js +2 -2
- package/dist/lib/ai/models.d.ts +1 -1
- package/dist/lib/ai/models.d.ts.map +1 -1
- package/dist/lib/ai/openai-reasoning.d.ts +2 -2
- package/dist/lib/ai/openai-reasoning.d.ts.map +1 -1
- package/dist/lib/db/schema.d.ts +1 -1
- package/dist/lib/db/schema.d.ts.map +1 -1
- package/dist/lib/tool-approval-decisions.d.ts +5 -0
- package/dist/lib/tool-approval-decisions.d.ts.map +1 -0
- package/dist/lib/types.d.ts +10 -0
- package/dist/lib/types.d.ts.map +1 -1
- package/dist/models/RBAgentsChatThread.d.ts +1 -0
- package/dist/models/RBAgentsChatThread.d.ts.map +1 -1
- package/dist/models/RBAgentsUsageEvent.d.ts +2 -1
- package/dist/models/RBAgentsUsageEvent.d.ts.map +1 -1
- package/dist/{models-BTzlEPg8.js → models-Bvdwv_p7.js} +14 -8
- package/dist/models.browser.js +6 -1
- package/dist/models.js +12 -1
- package/dist/openai-reasoning-CmTuRHwM.js +26 -0
- package/dist/routes.browser.js +8 -8
- package/dist/routes.js +8 -8
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +1 -1
- package/dist/tailwind-source.js +1 -1
- package/package.json +1 -1
- package/dist/handler-CVs03Ys2.js +0 -1568
- package/dist/handler-Z-tCrlQ_.js +0 -1562
- package/dist/openai-reasoning-BCA05blq.js +0 -19
package/dist/handler-Z-tCrlQ_.js
DELETED
|
@@ -1,1562 +0,0 @@
|
|
|
1
|
-
import { c as e, o as t } from "./message-visibility-zTseZa3P.js";
|
|
2
|
-
import { i as n } from "./openai-reasoning-BCA05blq.js";
|
|
3
|
-
import { t as r } from "./apiErrors-DKcH9vz9.js";
|
|
4
|
-
import { i, r as a, t as o } from "./chatCtx-C8Ba-LB7.js";
|
|
5
|
-
import { S as s, _ as c, a as l, b as u, f as d, g as f, h as p, l as m, m as h, n as g, s as _, v, x as y, y as b } from "./chatDb-DLQOzat8.js";
|
|
6
|
-
import { n as x, t as S } from "./resumableSse-CmmkOGyv.js";
|
|
7
|
-
import { Output as C, convertToModelMessages as ee, createUIMessageStream as te, extractReasoningMiddleware as w, generateText as ne, smoothStream as T, stepCountIs as re, streamObject as E, streamText as ie, tool as D, wrapLanguageModel as O } from "ai";
|
|
8
|
-
import { getTenantFilesystemDb as k } from "@rpcbase/db";
|
|
9
|
-
import { createHash as ae, randomUUID as A } from "node:crypto";
|
|
10
|
-
import { GridFSBucket as j, ObjectId as oe } from "mongodb";
|
|
11
|
-
import { createGoogleGenerativeAI as M } from "@ai-sdk/google";
|
|
12
|
-
import { openai as N } from "@ai-sdk/openai";
|
|
13
|
-
import { createXai as se } from "@ai-sdk/xai";
|
|
14
|
-
import { z as P } from "zod";
|
|
15
|
-
//#region src/api/chat/models.ts
|
|
16
|
-
var F = /-thinking$/, ce = "openai/", le = "google/", I = "xai/", L = new Set([
|
|
17
|
-
"openai/gpt-5.4-mini",
|
|
18
|
-
"openai/gpt-5.5",
|
|
19
|
-
"google/gemini-3.5-flash",
|
|
20
|
-
"xai/grok-4.3-thinking"
|
|
21
|
-
]), ue = (e) => e.startsWith(ce), de = (e) => e.startsWith(le), fe = (e) => e.startsWith(I), pe = (e) => e.endsWith("-thinking"), me = (e) => e.includes("/") ? ue(e) || de(e) || fe(e) : !1, R = se({
|
|
22
|
-
baseURL: process.env.XAI_BASE_URL ?? "https://api.x.ai/v1",
|
|
23
|
-
apiKey: process.env.XAI_API_KEY
|
|
24
|
-
}), z = M({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY }), he = (e) => {
|
|
25
|
-
if (ue(e)) return N.responses(e.slice(ce.length));
|
|
26
|
-
if (de(e)) {
|
|
27
|
-
let t = e.slice(le.length).replace(F, ""), n = z.chat(t);
|
|
28
|
-
return pe(e) ? O({
|
|
29
|
-
model: n,
|
|
30
|
-
middleware: w({ tagName: "thinking" })
|
|
31
|
-
}) : n;
|
|
32
|
-
}
|
|
33
|
-
if (fe(e)) {
|
|
34
|
-
let t = e.slice(I.length).replace(F, "");
|
|
35
|
-
return pe(e) ? R.responses(t) : R.chat(t);
|
|
36
|
-
}
|
|
37
|
-
throw Error(`Unsupported modelId: ${e}`);
|
|
38
|
-
}, ge = () => N.chat("gpt-5.4-mini"), B = () => N.chat(process.env.AGENT_SDK_ARTIFACT_MODEL ?? "gpt-5.4-mini"), V = "\nArtifacts is a special user interface mode that helps users with writing, editing, and other content creation tasks. When artifact is open, it is on the right side of the screen, while the conversation is on the left side. When creating, editing, or updating documents, changes are reflected in real-time on the artifacts and visible to the user.\n\nWhen asked to write code, always use artifacts. When writing code, specify the language in the backticks, e.g. ```python`code here```. The default language is Python. Other languages are not yet supported, so let the user know if they request a different language.\n\nCritical rules:\n- Only call one artifact tool per response.\n- Do not update or edit a document immediately after creating it. Wait for user feedback or an explicit request to modify it.\n- After creating, editing, or updating an artifact, do not repeat the full artifact content in chat. The user can already see it.\n\nThis is a guide for using artifacts tools: `createDocument`, `editDocument`, `updateDocument`, and `requestSuggestions`, which render content on artifacts beside the conversation.\n\n**When to use `createDocument`:**\n- For substantial content (>10 lines) or code\n- For content users will likely save/reuse (emails, code, essays, etc.)\n- When explicitly requested to create a document\n- For when content contains a single code snippet\n- Use kind \"code\" for programming, \"text\" for writing, and \"sheet\" for tabular/CSV data\n\n**When NOT to use `createDocument`:**\n- For informational/explanatory content\n- For conversational responses\n- When asked to keep it in chat\n\n**Using `editDocument`:**\n- Prefer this for targeted edits to an existing artifact\n- For scripts: fixing bugs, adding/removing lines, renaming variables, adding logs\n- For documents: fixing typos, rewording paragraphs, inserting or replacing sections\n- Provide an exact `old_string` and `new_string`\n- Include enough surrounding context in `old_string` to make the match unique\n- Use `replace_all: true` only for deliberate repeated replacements, like renaming a variable everywhere\n\n**Using `updateDocument`:**\n- Default to full document rewrites for major changes\n- Use `editDocument` instead for specific, isolated changes\n- Follow user instructions for which parts to modify\n\n**When NOT to use `editDocument` or `updateDocument`:**\n- Immediately after creating a document\n- Without an explicit user request to modify the artifact\n\n**Using `requestSuggestions`:**\n- ONLY use when the user explicitly asks for suggestions on an existing document\n- Requires a valid document ID from a previously created document\n- Never use for general questions or information requests\n", H = "You are a friendly assistant! Keep your responses concise and helpful.\n\nWhen asked to write, create, or help with something, just do it directly. Don't ask clarifying questions unless absolutely necessary - make reasonable assumptions and proceed with the task.", U = (e) => `\
|
|
39
|
-
About the origin of user's request:
|
|
40
|
-
- lat: ${e.latitude ?? "unknown"}
|
|
41
|
-
- lon: ${e.longitude ?? "unknown"}
|
|
42
|
-
- city: ${e.city ?? "unknown"}
|
|
43
|
-
- country: ${e.country ?? "unknown"}
|
|
44
|
-
`, _e = ({ selectedChatModel: e, requestHints: t, agentInstructions: n, knowledge: r }) => {
|
|
45
|
-
let i = U(t), a = [n?.trim() ? `Agent instructions:\n${n.trim()}` : "", r?.trim() ? `Knowledge context:\n${r.trim()}` : ""].filter(Boolean).join("\n\n");
|
|
46
|
-
if (e.includes("reasoning") || e.includes("thinking")) {
|
|
47
|
-
let t = e.startsWith("google/") && e.includes("thinking") ? `${H}\n\nWhen you reason, put your reasoning inside <thinking>...</thinking> tags. Then provide your final answer outside of those tags.\n\n${i}` : `${H}\n\n${i}`;
|
|
48
|
-
return a ? `${t}\n\n${a}` : t;
|
|
49
|
-
}
|
|
50
|
-
let o = `${H}\n\n${i}\n\n${V}`;
|
|
51
|
-
return a ? `${o}\n\n${a}` : o;
|
|
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
|
-
let n = "document";
|
|
54
|
-
return t === "code" ? n = "script" : t === "sheet" && (n = "spreadsheet"), `Rewrite the following ${n} based on the given prompt.
|
|
55
|
-
|
|
56
|
-
${e}`;
|
|
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", W = (e) => !!e && typeof e == "object" && !Array.isArray(e), G = (e) => typeof e == "string" && e.trim() ? e.trim() : null, Ee = (e) => {
|
|
58
|
-
let t = G((W(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
|
-
}, K = (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
|
-
}, De = (e) => (Array.isArray(e.parts) ? e.parts : []).flatMap((e) => {
|
|
73
|
-
if (!W(e)) {
|
|
74
|
-
let t = K(e);
|
|
75
|
-
return t ? [t] : [];
|
|
76
|
-
}
|
|
77
|
-
let t = G(e.type) ?? "part", n = K(e.text);
|
|
78
|
-
if (n) return [`${t}: ${n}`];
|
|
79
|
-
let r = K(e.output);
|
|
80
|
-
if (r) return [`${t}: ${r}`];
|
|
81
|
-
let i = K(e.result);
|
|
82
|
-
if (i) return [`${t}: ${i}`];
|
|
83
|
-
let a = K(e.content);
|
|
84
|
-
if (a) return [`${t}: ${a}`];
|
|
85
|
-
let o = K(e, 1e3);
|
|
86
|
-
return o ? [`${t}: ${o}`] : [];
|
|
87
|
-
}).join("\n").trim(), Oe = (e) => e.reduce((e, t) => e + De(t).length, 0), ke = (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
|
-
}, 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
|
-
} : {
|
|
97
|
-
maxMessages: Se,
|
|
98
|
-
maxEstimatedChars: Ce,
|
|
99
|
-
maxSummaryChars: we
|
|
100
|
-
}, je = (e) => W(e) && e.type === "agent-runtime-history-compaction" && e.version === 1 && typeof e.summary == "string", Me = (e) => je(e) ? e : W(e) && je(e.historyCompaction) ? e.historyCompaction : null, Ne = (e, t) => t ? W(e) && !je(e) ? {
|
|
101
|
-
...e,
|
|
102
|
-
historyCompaction: t
|
|
103
|
-
} : { historyCompaction: t } : e ?? null, Pe = (e) => G(e.id), Fe = (e, t) => {
|
|
104
|
-
let n = G(t?.compactedThroughMessageId);
|
|
105
|
-
return n ? e.findIndex((e) => Pe(e) === n) : -1;
|
|
106
|
-
}, Ie = (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 && Oe(e.slice(i)) > t.maxEstimatedChars;) i += 1;
|
|
109
|
-
return i;
|
|
110
|
-
}, Le = (e) => {
|
|
111
|
-
let t = G(e.role) ?? "message", n = Ee(e), r = De(e);
|
|
112
|
-
return `${n ? `${t} (${n})` : t}:\n${r || "[non-text content]"}`;
|
|
113
|
-
}, Re = ({ previousContext: e, messagesToCompact: t, limits: n }) => {
|
|
114
|
-
let r = e?.summary?.trim(), i = t.map(Le).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
|
-
}, ze = (e) => ({
|
|
117
|
-
id: `${Te}:${G(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
|
-
}), Be = (e, t) => t?.summary.trim() ? [ze(t), ...e] : e, Ve = ({ messages: e, previousContext: t, limits: n }) => {
|
|
134
|
-
let r = Fe(e, t), i = r >= 0 ? e.slice(r + 1) : e;
|
|
135
|
-
if (!(i.length > n.maxMessages || Oe(i) > n.maxEstimatedChars)) return {
|
|
136
|
-
messages: Be(i, t),
|
|
137
|
-
context: t
|
|
138
|
-
};
|
|
139
|
-
let a = Ie(i, n);
|
|
140
|
-
if (a <= 0) return {
|
|
141
|
-
messages: Be(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: Re({
|
|
148
|
-
previousContext: t,
|
|
149
|
-
messagesToCompact: o,
|
|
150
|
-
limits: n
|
|
151
|
-
}),
|
|
152
|
-
compactedThroughMessageId: c ? Pe(c) : t?.compactedThroughMessageId ?? null,
|
|
153
|
-
compactedThroughMessageCreatedAt: c ? Ee(c) : t?.compactedThroughMessageCreatedAt ?? null,
|
|
154
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
155
|
-
messageCount: e.length
|
|
156
|
-
};
|
|
157
|
-
return {
|
|
158
|
-
messages: Be(s, l),
|
|
159
|
-
context: l
|
|
160
|
-
};
|
|
161
|
-
}, He = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: r, mode: i, messages: o, lastContext: s }) => {
|
|
162
|
-
let c = a().historyCompaction;
|
|
163
|
-
if (c === !1 || c && c.enabled === !1) return {
|
|
164
|
-
messages: o,
|
|
165
|
-
lastContext: s ?? null,
|
|
166
|
-
lastContextChanged: !1
|
|
167
|
-
};
|
|
168
|
-
let l = Ae(c), u = Me(s);
|
|
169
|
-
try {
|
|
170
|
-
let a = typeof c == "object" && typeof c.compact == "function" ? await c.compact({
|
|
171
|
-
ctx: e,
|
|
172
|
-
chatId: t,
|
|
173
|
-
agent: n,
|
|
174
|
-
selectedChatModel: r,
|
|
175
|
-
mode: i,
|
|
176
|
-
messages: o,
|
|
177
|
-
previousContext: u,
|
|
178
|
-
limits: l
|
|
179
|
-
}) : Ve({
|
|
180
|
-
messages: o,
|
|
181
|
-
previousContext: u,
|
|
182
|
-
limits: l
|
|
183
|
-
}), d = Array.isArray(a.messages) ? a.messages : o, f = a.context === void 0 ? u : a.context;
|
|
184
|
-
return {
|
|
185
|
-
messages: d,
|
|
186
|
-
lastContext: Ne(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
|
-
}, Ue = [
|
|
197
|
-
"text",
|
|
198
|
-
"code",
|
|
199
|
-
"sheet"
|
|
200
|
-
], We = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, q = () => !We(process.env.AGENT_SDK_LIVE_TOOLS) && (We(process.env.PLAYWRIGHT) || process.env.NODE_ENV === "test"), Ge = (e) => !!(e && typeof e == "object" && !Array.isArray(e)), J = (e) => e instanceof Error ? {
|
|
201
|
-
errorName: e.name,
|
|
202
|
-
errorMessage: e.message,
|
|
203
|
-
errorStack: e.stack,
|
|
204
|
-
errorCause: e.cause
|
|
205
|
-
} : { errorValue: e }, Y = (e, t) => {
|
|
206
|
-
console.error(`[agents-sdk:getWeather] ${e}`, t);
|
|
207
|
-
}, Ke = async ({ system: e, prompt: t, dataStream: n, providerOptions: r }) => {
|
|
208
|
-
if (q()) {
|
|
209
|
-
let e = `Stub document: ${t}`;
|
|
210
|
-
return n.write({
|
|
211
|
-
type: "data-textDelta",
|
|
212
|
-
data: e,
|
|
213
|
-
transient: !0
|
|
214
|
-
}), e;
|
|
215
|
-
}
|
|
216
|
-
let i = "", { fullStream: a } = ie({
|
|
217
|
-
model: B(),
|
|
218
|
-
system: e,
|
|
219
|
-
experimental_transform: T({ chunking: "word" }),
|
|
220
|
-
prompt: t,
|
|
221
|
-
providerOptions: r
|
|
222
|
-
});
|
|
223
|
-
for await (let e of a) e.type === "text-delta" && (i += e.text, n.write({
|
|
224
|
-
type: "data-textDelta",
|
|
225
|
-
data: e.text,
|
|
226
|
-
transient: !0
|
|
227
|
-
}));
|
|
228
|
-
return i;
|
|
229
|
-
}, qe = async ({ system: e, prompt: t, dataStream: n }) => {
|
|
230
|
-
if (q()) {
|
|
231
|
-
let e = `print("Stub code for: ${t}")\n`;
|
|
232
|
-
return n.write({
|
|
233
|
-
type: "data-codeDelta",
|
|
234
|
-
data: e,
|
|
235
|
-
transient: !0
|
|
236
|
-
}), e;
|
|
237
|
-
}
|
|
238
|
-
let r = "", { fullStream: i } = E({
|
|
239
|
-
model: B(),
|
|
240
|
-
system: e,
|
|
241
|
-
prompt: t,
|
|
242
|
-
schema: P.object({ code: P.string() })
|
|
243
|
-
});
|
|
244
|
-
for await (let e of i) {
|
|
245
|
-
if (e.type !== "object") continue;
|
|
246
|
-
let t = e.object?.code;
|
|
247
|
-
t && (n.write({
|
|
248
|
-
type: "data-codeDelta",
|
|
249
|
-
data: t ?? "",
|
|
250
|
-
transient: !0
|
|
251
|
-
}), r = t);
|
|
252
|
-
}
|
|
253
|
-
return r;
|
|
254
|
-
}, Je = async ({ system: e, prompt: t, dataStream: n }) => {
|
|
255
|
-
if (q()) {
|
|
256
|
-
let e = `name,value\n${t.replaceAll(",", " ")},1\n`;
|
|
257
|
-
return n.write({
|
|
258
|
-
type: "data-sheetDelta",
|
|
259
|
-
data: e,
|
|
260
|
-
transient: !0
|
|
261
|
-
}), e;
|
|
262
|
-
}
|
|
263
|
-
let r = "", { fullStream: i } = E({
|
|
264
|
-
model: B(),
|
|
265
|
-
system: e,
|
|
266
|
-
prompt: t,
|
|
267
|
-
schema: P.object({ csv: P.string().describe("CSV data") })
|
|
268
|
-
});
|
|
269
|
-
for await (let e of i) {
|
|
270
|
-
if (e.type !== "object") continue;
|
|
271
|
-
let t = e.object?.csv;
|
|
272
|
-
t && (n.write({
|
|
273
|
-
type: "data-sheetDelta",
|
|
274
|
-
data: t,
|
|
275
|
-
transient: !0
|
|
276
|
-
}), r = t);
|
|
277
|
-
}
|
|
278
|
-
return n.write({
|
|
279
|
-
type: "data-sheetDelta",
|
|
280
|
-
data: r,
|
|
281
|
-
transient: !0
|
|
282
|
-
}), r;
|
|
283
|
-
}, Ye = async (e) => {
|
|
284
|
-
let t = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(e)}&count=1&language=en&format=json`;
|
|
285
|
-
try {
|
|
286
|
-
let n = await fetch(t);
|
|
287
|
-
if (!n.ok) return Y("Geocoding request failed.", {
|
|
288
|
-
city: e,
|
|
289
|
-
status: n.status,
|
|
290
|
-
statusText: n.statusText
|
|
291
|
-
}), null;
|
|
292
|
-
let r = await n.json().catch((t) => (Y("Geocoding response parse failed.", {
|
|
293
|
-
city: e,
|
|
294
|
-
...J(t)
|
|
295
|
-
}), null)), i = Ge(r) && Array.isArray(r.results) ? r.results : [];
|
|
296
|
-
if (i.length === 0) return Y("Geocoding returned no results.", { city: e }), null;
|
|
297
|
-
let a = i[0];
|
|
298
|
-
if (!Ge(a)) return Y("Geocoding returned an invalid result shape.", {
|
|
299
|
-
city: e,
|
|
300
|
-
result: a
|
|
301
|
-
}), null;
|
|
302
|
-
let o = a.latitude, s = a.longitude;
|
|
303
|
-
return typeof o != "number" || typeof s != "number" ? (Y("Geocoding result did not include numeric coordinates.", {
|
|
304
|
-
city: e,
|
|
305
|
-
latitude: o,
|
|
306
|
-
longitude: s
|
|
307
|
-
}), null) : {
|
|
308
|
-
latitude: o,
|
|
309
|
-
longitude: s
|
|
310
|
-
};
|
|
311
|
-
} catch (t) {
|
|
312
|
-
return Y("Geocoding request threw.", {
|
|
313
|
-
city: e,
|
|
314
|
-
...J(t)
|
|
315
|
-
}), null;
|
|
316
|
-
}
|
|
317
|
-
}, Xe = ({ ctx: e, dataStream: t, requestHints: n }) => {
|
|
318
|
-
let r = o(e), i = (t) => ({
|
|
319
|
-
input: t,
|
|
320
|
-
requestHints: n,
|
|
321
|
-
tenantId: r.tenantId,
|
|
322
|
-
userId: r.userId,
|
|
323
|
-
route: e.req?.path ?? e.req?.originalUrl ?? e.req?.url
|
|
324
|
-
}), a = async (t) => {
|
|
325
|
-
let n = await _(e, t);
|
|
326
|
-
return n.length > 0 ? n.at(-1) ?? null : null;
|
|
327
|
-
}, s = D({
|
|
328
|
-
description: "Get the current weather at a location. Use this for direct weather or forecast requests. You can provide either coordinates or a city name.",
|
|
329
|
-
inputSchema: P.object({
|
|
330
|
-
latitude: P.number().optional(),
|
|
331
|
-
longitude: P.number().optional(),
|
|
332
|
-
city: P.string().describe("City name (e.g., 'San Francisco', 'New York', 'London')").optional()
|
|
333
|
-
}),
|
|
334
|
-
needsApproval: !0,
|
|
335
|
-
execute: async (e) => {
|
|
336
|
-
let t, n;
|
|
337
|
-
if (e.city) {
|
|
338
|
-
let r = await Ye(e.city);
|
|
339
|
-
if (!r) return Y("Tool returned an error because city geocoding failed.", {
|
|
340
|
-
...i(e),
|
|
341
|
-
city: e.city
|
|
342
|
-
}), { error: `Could not find coordinates for "${e.city}". Please check the city name.` };
|
|
343
|
-
t = r.latitude, n = r.longitude;
|
|
344
|
-
} else if (e.latitude !== void 0 && e.longitude !== void 0) t = e.latitude, n = e.longitude;
|
|
345
|
-
else return Y("Tool returned an error because location input was missing.", { ...i(e) }), { error: "Please provide either a city name or both latitude and longitude coordinates." };
|
|
346
|
-
try {
|
|
347
|
-
let r = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${t}&longitude=${n}¤t=temperature_2m&hourly=temperature_2m&daily=sunrise,sunset&timezone=auto`);
|
|
348
|
-
if (!r.ok) return Y("Forecast request failed.", {
|
|
349
|
-
...i(e),
|
|
350
|
-
latitude: t,
|
|
351
|
-
longitude: n,
|
|
352
|
-
status: r.status,
|
|
353
|
-
statusText: r.statusText
|
|
354
|
-
}), { error: "Weather lookup failed. Please try again." };
|
|
355
|
-
let a = await r.json().catch((r) => (Y("Forecast response parse failed.", {
|
|
356
|
-
...i(e),
|
|
357
|
-
latitude: t,
|
|
358
|
-
longitude: n,
|
|
359
|
-
...J(r)
|
|
360
|
-
}), null));
|
|
361
|
-
return Ge(a) ? ("city" in e && (a.cityName = e.city), a) : (Y("Tool returned an error because forecast response was invalid.", {
|
|
362
|
-
...i(e),
|
|
363
|
-
latitude: t,
|
|
364
|
-
longitude: n,
|
|
365
|
-
weatherData: a
|
|
366
|
-
}), { error: "Weather lookup failed. Please try again." });
|
|
367
|
-
} catch (r) {
|
|
368
|
-
return Y("Forecast request threw.", {
|
|
369
|
-
...i(e),
|
|
370
|
-
latitude: t,
|
|
371
|
-
longitude: n,
|
|
372
|
-
...J(r)
|
|
373
|
-
}), { error: "Weather lookup failed. Please try again." };
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
}), l = D({
|
|
377
|
-
description: "Create an artifact for writing or content creation. Use kind 'code' for programming, 'text' for writing, and 'sheet' for spreadsheets or tabular data.",
|
|
378
|
-
inputSchema: P.object({
|
|
379
|
-
title: P.string().describe("The title of the artifact"),
|
|
380
|
-
kind: P.enum(Ue).describe("Use 'code' for programming, 'text' for prose, and 'sheet' for CSV/tabular data")
|
|
381
|
-
}),
|
|
382
|
-
execute: async ({ title: n, kind: r }) => {
|
|
383
|
-
let i = A();
|
|
384
|
-
t.write({
|
|
385
|
-
type: "data-kind",
|
|
386
|
-
data: r,
|
|
387
|
-
transient: !0
|
|
388
|
-
}), t.write({
|
|
389
|
-
type: "data-id",
|
|
390
|
-
data: i,
|
|
391
|
-
transient: !0
|
|
392
|
-
}), t.write({
|
|
393
|
-
type: "data-title",
|
|
394
|
-
data: n,
|
|
395
|
-
transient: !0
|
|
396
|
-
}), t.write({
|
|
397
|
-
type: "data-clear",
|
|
398
|
-
data: null,
|
|
399
|
-
transient: !0
|
|
400
|
-
});
|
|
401
|
-
let a = "";
|
|
402
|
-
return r === "text" ? a = await Ke({
|
|
403
|
-
system: "Write about the given topic. Markdown is supported. Use headings wherever appropriate.",
|
|
404
|
-
prompt: n,
|
|
405
|
-
dataStream: t
|
|
406
|
-
}) : r === "code" ? a = await qe({
|
|
407
|
-
system: ve,
|
|
408
|
-
prompt: n,
|
|
409
|
-
dataStream: t
|
|
410
|
-
}) : r === "sheet" && (a = await Je({
|
|
411
|
-
system: ye,
|
|
412
|
-
prompt: n,
|
|
413
|
-
dataStream: t
|
|
414
|
-
})), await p(e, {
|
|
415
|
-
id: i,
|
|
416
|
-
title: n,
|
|
417
|
-
kind: r,
|
|
418
|
-
content: a
|
|
419
|
-
}), t.write({
|
|
420
|
-
type: "data-finish",
|
|
421
|
-
data: null,
|
|
422
|
-
transient: !0
|
|
423
|
-
}), {
|
|
424
|
-
id: i,
|
|
425
|
-
title: n,
|
|
426
|
-
kind: r,
|
|
427
|
-
content: r === "code" ? "A script was created and is now visible to the user." : "A document was created and is now visible to the user."
|
|
428
|
-
};
|
|
429
|
-
}
|
|
430
|
-
}), u = D({
|
|
431
|
-
description: "Fully rewrite an existing artifact with the given description. Use editDocument instead for targeted find-and-replace changes.",
|
|
432
|
-
inputSchema: P.object({
|
|
433
|
-
id: P.string().describe("The ID of the artifact to rewrite"),
|
|
434
|
-
description: P.string().default("Improve the content").describe("The description of changes that need to be made")
|
|
435
|
-
}),
|
|
436
|
-
execute: async ({ id: n, description: r }) => {
|
|
437
|
-
let i = await a(n);
|
|
438
|
-
if (!i) return { error: "Document not found" };
|
|
439
|
-
let o = i.kind;
|
|
440
|
-
if (!Ue.includes(o)) return { error: `Unsupported document kind: ${i.kind}` };
|
|
441
|
-
t.write({
|
|
442
|
-
type: "data-clear",
|
|
443
|
-
data: null,
|
|
444
|
-
transient: !0
|
|
445
|
-
});
|
|
446
|
-
let s = "";
|
|
447
|
-
return o === "text" ? s = await Ke({
|
|
448
|
-
system: be(i.content, i.kind),
|
|
449
|
-
prompt: r,
|
|
450
|
-
dataStream: t,
|
|
451
|
-
providerOptions: { openai: { prediction: {
|
|
452
|
-
type: "content",
|
|
453
|
-
content: i.content
|
|
454
|
-
} } }
|
|
455
|
-
}) : o === "code" ? s = await qe({
|
|
456
|
-
system: be(i.content, i.kind),
|
|
457
|
-
prompt: r,
|
|
458
|
-
dataStream: t
|
|
459
|
-
}) : o === "sheet" && (s = await Je({
|
|
460
|
-
system: be(i.content, i.kind),
|
|
461
|
-
prompt: r,
|
|
462
|
-
dataStream: t
|
|
463
|
-
})), await p(e, {
|
|
464
|
-
id: i.id,
|
|
465
|
-
title: i.title,
|
|
466
|
-
kind: i.kind,
|
|
467
|
-
content: s
|
|
468
|
-
}), t.write({
|
|
469
|
-
type: "data-finish",
|
|
470
|
-
data: null,
|
|
471
|
-
transient: !0
|
|
472
|
-
}), {
|
|
473
|
-
id: i.id,
|
|
474
|
-
title: i.title,
|
|
475
|
-
kind: i.kind,
|
|
476
|
-
content: i.kind === "code" ? "The script has been updated successfully." : "The document has been updated successfully."
|
|
477
|
-
};
|
|
478
|
-
}
|
|
479
|
-
});
|
|
480
|
-
return {
|
|
481
|
-
getWeather: s,
|
|
482
|
-
createDocument: l,
|
|
483
|
-
editDocument: D({
|
|
484
|
-
description: "Make a targeted edit to an existing artifact by replacing an exact string. Prefer this over updateDocument for small changes, fixes, renames, and isolated edits.",
|
|
485
|
-
inputSchema: P.object({
|
|
486
|
-
id: P.string().describe("The ID of the artifact to edit"),
|
|
487
|
-
old_string: P.string().min(1).describe("Exact string to find. Include enough surrounding context to make the match unique."),
|
|
488
|
-
new_string: P.string().describe("Replacement string"),
|
|
489
|
-
replace_all: P.boolean().optional().describe("Replace all occurrences instead of only the first one")
|
|
490
|
-
}),
|
|
491
|
-
execute: async ({ id: n, old_string: r, new_string: i, replace_all: o }) => {
|
|
492
|
-
let s = await a(n);
|
|
493
|
-
if (!s) return { error: "Document not found" };
|
|
494
|
-
if (!s.content) return { error: "Document has no content" };
|
|
495
|
-
let c = s.kind;
|
|
496
|
-
if (!Ue.includes(c)) return { error: `Unsupported document kind: ${s.kind}` };
|
|
497
|
-
if (!s.content.includes(r)) return { error: "old_string not found in document" };
|
|
498
|
-
let l = o ? s.content.replaceAll(r, i) : s.content.replace(r, i);
|
|
499
|
-
return await p(e, {
|
|
500
|
-
id: s.id,
|
|
501
|
-
title: s.title,
|
|
502
|
-
kind: s.kind,
|
|
503
|
-
content: l
|
|
504
|
-
}), t.write({
|
|
505
|
-
type: "data-clear",
|
|
506
|
-
data: null,
|
|
507
|
-
transient: !0
|
|
508
|
-
}), c === "code" ? t.write({
|
|
509
|
-
type: "data-codeDelta",
|
|
510
|
-
data: l,
|
|
511
|
-
transient: !0
|
|
512
|
-
}) : c === "sheet" ? t.write({
|
|
513
|
-
type: "data-sheetDelta",
|
|
514
|
-
data: l,
|
|
515
|
-
transient: !0
|
|
516
|
-
}) : t.write({
|
|
517
|
-
type: "data-textDelta",
|
|
518
|
-
data: l,
|
|
519
|
-
transient: !0
|
|
520
|
-
}), t.write({
|
|
521
|
-
type: "data-finish",
|
|
522
|
-
data: null,
|
|
523
|
-
transient: !0
|
|
524
|
-
}), {
|
|
525
|
-
id: s.id,
|
|
526
|
-
title: s.title,
|
|
527
|
-
kind: s.kind,
|
|
528
|
-
content: s.kind === "code" ? "The script has been edited successfully." : "The document has been edited successfully."
|
|
529
|
-
};
|
|
530
|
-
}
|
|
531
|
-
}),
|
|
532
|
-
updateDocument: u,
|
|
533
|
-
requestSuggestions: D({
|
|
534
|
-
description: "Request writing suggestions for an existing document artifact. Only use this when the user explicitly asks to improve or get suggestions for a document they have already created. Never use for general questions.",
|
|
535
|
-
inputSchema: P.object({ documentId: P.string().describe("The UUID of an existing document artifact that was previously created with createDocument") }),
|
|
536
|
-
execute: async ({ documentId: n }) => {
|
|
537
|
-
let i = await a(n);
|
|
538
|
-
if (!i?.content) return { error: "Document not found" };
|
|
539
|
-
if (q()) {
|
|
540
|
-
let a = {
|
|
541
|
-
originalText: "Stub original sentence.",
|
|
542
|
-
suggestedText: "Stub suggested sentence.",
|
|
543
|
-
description: "Stub suggestion",
|
|
544
|
-
id: A(),
|
|
545
|
-
documentId: n,
|
|
546
|
-
documentCreatedAt: i.createdAt,
|
|
547
|
-
isResolved: !1,
|
|
548
|
-
userId: r.userId,
|
|
549
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
550
|
-
};
|
|
551
|
-
return t.write({
|
|
552
|
-
type: "data-suggestion",
|
|
553
|
-
data: a,
|
|
554
|
-
transient: !0
|
|
555
|
-
}), await c(e, {
|
|
556
|
-
documentId: n,
|
|
557
|
-
suggestions: [a]
|
|
558
|
-
}), {
|
|
559
|
-
id: n,
|
|
560
|
-
title: i.title,
|
|
561
|
-
kind: i.kind,
|
|
562
|
-
message: "Suggestions have been added to the document"
|
|
563
|
-
};
|
|
564
|
-
}
|
|
565
|
-
let o = [], { partialOutputStream: s } = ie({
|
|
566
|
-
model: B(),
|
|
567
|
-
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.",
|
|
568
|
-
prompt: i.content,
|
|
569
|
-
output: C.array({ element: P.object({
|
|
570
|
-
originalSentence: P.string().describe("The original sentence"),
|
|
571
|
-
suggestedSentence: P.string().describe("The suggested sentence"),
|
|
572
|
-
description: P.string().describe("The description of the suggestion")
|
|
573
|
-
}) })
|
|
574
|
-
}), l = 0;
|
|
575
|
-
for await (let e of s) if (e) for (let a = l; a < e.length; a++) {
|
|
576
|
-
let s = e[a];
|
|
577
|
-
if (!s?.originalSentence || !s?.suggestedSentence || !s?.description) continue;
|
|
578
|
-
let c = {
|
|
579
|
-
originalText: s.originalSentence,
|
|
580
|
-
suggestedText: s.suggestedSentence,
|
|
581
|
-
description: s.description,
|
|
582
|
-
id: A(),
|
|
583
|
-
documentId: n,
|
|
584
|
-
documentCreatedAt: i.createdAt,
|
|
585
|
-
isResolved: !1,
|
|
586
|
-
userId: r.userId,
|
|
587
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
588
|
-
};
|
|
589
|
-
t.write({
|
|
590
|
-
type: "data-suggestion",
|
|
591
|
-
data: c,
|
|
592
|
-
transient: !0
|
|
593
|
-
}), o.push(c), l++;
|
|
594
|
-
}
|
|
595
|
-
return o.length > 0 && await c(e, {
|
|
596
|
-
documentId: n,
|
|
597
|
-
suggestions: o
|
|
598
|
-
}), {
|
|
599
|
-
id: n,
|
|
600
|
-
title: i.title,
|
|
601
|
-
kind: i.kind,
|
|
602
|
-
message: "Suggestions have been added to the document"
|
|
603
|
-
};
|
|
604
|
-
}
|
|
605
|
-
}),
|
|
606
|
-
webSearch: N.tools.webSearch({
|
|
607
|
-
externalWebAccess: !0,
|
|
608
|
-
searchContextSize: "medium",
|
|
609
|
-
userLocation: {
|
|
610
|
-
type: "approximate",
|
|
611
|
-
country: n.country ?? void 0,
|
|
612
|
-
city: n.city ?? void 0
|
|
613
|
-
}
|
|
614
|
-
})
|
|
615
|
-
};
|
|
616
|
-
}, Ze = "getWeather", Qe = "webSearch", $e = (e) => e.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase(), et = [
|
|
617
|
-
/\bweather\b/,
|
|
618
|
-
/\bforecast\b/,
|
|
619
|
-
/\btemperatures?\b/,
|
|
620
|
-
/\bmeteo\b/,
|
|
621
|
-
/\bquel temps\b/,
|
|
622
|
-
/\btemps fait\b/,
|
|
623
|
-
/\bil fait\b.*\b(temps|froid|chaud|beau|mauvais)\b/,
|
|
624
|
-
/\bpleut\b/,
|
|
625
|
-
/\bpluie\b/
|
|
626
|
-
], tt = (e) => {
|
|
627
|
-
let t = $e(e);
|
|
628
|
-
return t ? et.some((e) => e.test(t)) : !1;
|
|
629
|
-
}, nt = ({ activeTools: e, availableTools: t, userText: n }) => {
|
|
630
|
-
let r = Ze in t, i = e.includes(Ze), a = e.includes(Qe);
|
|
631
|
-
return !r || !i || !a || !tt(n) ? [...e] : e.filter((e) => e !== Qe);
|
|
632
|
-
}, rt = (e) => e ? !e.trim() : !0, it = (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(), at = (e) => {
|
|
633
|
-
let t = e.trim();
|
|
634
|
-
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;
|
|
635
|
-
}, ot = (e) => {
|
|
636
|
-
let t = e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").replace(/\s+/g, " ").trim();
|
|
637
|
-
return t === "hi" || t === "hello" || t === "hey" || t === "salut" || t === "bonjour";
|
|
638
|
-
}, st = (e) => {
|
|
639
|
-
let t = e.trim();
|
|
640
|
-
return !t || ot(t) ? "" : at(t.replaceAll("\n", " ").replaceAll("\r", " ").split(/\s+/).filter((e) => e.trim() !== "").slice(0, 5).join(" "));
|
|
641
|
-
}, ct = "/api/rb/agents/chat";
|
|
642
|
-
P.any(), P.any();
|
|
643
|
-
var lt = 1024 * 1024 * 20, ut = 1e5, dt = /^\/api\/rb\/files\/([^/]+)\/?$/, ft = "test-model", pt = "openai/gpt-5.4-mini", mt = 9e3, ht = new Set([
|
|
644
|
-
"start",
|
|
645
|
-
"start-step",
|
|
646
|
-
"finish-step",
|
|
647
|
-
"finish",
|
|
648
|
-
"raw"
|
|
649
|
-
]), gt = async (e) => new Promise((t) => setTimeout(t, e)), _t = async (e, t) => {
|
|
650
|
-
let n = x(t);
|
|
651
|
-
n && !n.isDone || await y(e, {
|
|
652
|
-
chatId: t,
|
|
653
|
-
isStreaming: !1
|
|
654
|
-
});
|
|
655
|
-
}, vt = (e) => e ? e === "1" || e.toLowerCase() === "true" || e.toLowerCase() === "yes" : !1, X = (e) => typeof e == "string" && e.trim() || null, yt = () => {
|
|
656
|
-
let e = a().chatModels;
|
|
657
|
-
if (!e?.length) return L;
|
|
658
|
-
let t = /* @__PURE__ */ new Set();
|
|
659
|
-
for (let n of e) {
|
|
660
|
-
let e = X(typeof n == "string" ? n : n.id);
|
|
661
|
-
e && t.add(e);
|
|
662
|
-
}
|
|
663
|
-
return t;
|
|
664
|
-
}, bt = (e) => {
|
|
665
|
-
if (typeof e == "boolean") return e;
|
|
666
|
-
let t = X(e)?.toLowerCase();
|
|
667
|
-
return t ? t === "true" ? !0 : t === "false" ? !1 : null : null;
|
|
668
|
-
}, xt = (e) => {
|
|
669
|
-
let t = e.req?.session?.user?.currentTenantId;
|
|
670
|
-
return X(t);
|
|
671
|
-
}, St = (e) => {
|
|
672
|
-
let t = e.req?.session?.user?.id;
|
|
673
|
-
return X(t);
|
|
674
|
-
}, Ct = () => X(process.env.RB_FILESYSTEM_BUCKET_NAME) ?? "fs", wt = (e) => ae("sha256").update(Buffer.from(e)).digest("hex"), Tt = (e) => {
|
|
675
|
-
let t = e.trim();
|
|
676
|
-
if (!t) return null;
|
|
677
|
-
let n;
|
|
678
|
-
try {
|
|
679
|
-
n = new URL(t);
|
|
680
|
-
} catch {
|
|
681
|
-
try {
|
|
682
|
-
n = new URL(t, "http://localhost");
|
|
683
|
-
} catch {
|
|
684
|
-
return null;
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
let r = dt.exec(n.pathname);
|
|
688
|
-
if (!r) return null;
|
|
689
|
-
let i = X(decodeURIComponent(r[1]));
|
|
690
|
-
return i ? {
|
|
691
|
-
fileId: i,
|
|
692
|
-
uploadKey: X(n.searchParams.get("rb-upload-key"))
|
|
693
|
-
} : null;
|
|
694
|
-
}, Et = async ({ ctx: e, fileId: t, uploadKey: n }) => {
|
|
695
|
-
let r = xt(e);
|
|
696
|
-
if (!r) throw Error("tenant_missing");
|
|
697
|
-
let i;
|
|
698
|
-
try {
|
|
699
|
-
i = new oe(t);
|
|
700
|
-
} catch {
|
|
701
|
-
throw Error("invalid_file_id");
|
|
702
|
-
}
|
|
703
|
-
let a = (await k(r)).db;
|
|
704
|
-
if (!a) throw Error("filesystem_db_unavailable");
|
|
705
|
-
let o = new j(a, { bucketName: Ct() }), [s] = await o.find({ _id: i }).limit(1).toArray();
|
|
706
|
-
if (!s) throw Error("file_not_found");
|
|
707
|
-
let c = bt(s?.metadata?.isPublic) ?? !1, l = St(e), u = X(s?.metadata?.userId), d = X(s?.metadata?.ownerKeyHash);
|
|
708
|
-
if (!c) {
|
|
709
|
-
let e = !!(l && u && l === u), t = !!(n && d && wt(n) === d);
|
|
710
|
-
if (!e && !t) throw Error("unauthorized");
|
|
711
|
-
}
|
|
712
|
-
let f = X(s?.metadata?.mimeType), p = [], m = 0;
|
|
713
|
-
return await new Promise((e, t) => {
|
|
714
|
-
let n = o.openDownloadStream(i);
|
|
715
|
-
n.on("data", (e) => {
|
|
716
|
-
if (m += e.length, m > lt) {
|
|
717
|
-
n.destroy(/* @__PURE__ */ Error("attachment_too_large"));
|
|
718
|
-
return;
|
|
719
|
-
}
|
|
720
|
-
p.push(e);
|
|
721
|
-
}), n.on("end", () => e()), n.on("error", (e) => t(e));
|
|
722
|
-
}), {
|
|
723
|
-
data: Buffer.concat(p, m),
|
|
724
|
-
mimeType: f
|
|
725
|
-
};
|
|
726
|
-
}, Dt = async (e, t) => {
|
|
727
|
-
let n = Array.isArray(t) ? t : [], r = [];
|
|
728
|
-
for (let t of n) {
|
|
729
|
-
if (!t || typeof t != "object" || !("role" in t) || t.role !== "user") continue;
|
|
730
|
-
let n = Array.isArray(t.content) ? t.content : null;
|
|
731
|
-
if (n) for (let t of n) {
|
|
732
|
-
if (!t || typeof t != "object" || t.type !== "file" || typeof t.data != "string") continue;
|
|
733
|
-
let n = Tt(t.data);
|
|
734
|
-
n && r.push((async () => {
|
|
735
|
-
let { data: r, mimeType: i } = await Et({
|
|
736
|
-
ctx: e,
|
|
737
|
-
...n
|
|
738
|
-
});
|
|
739
|
-
t.data = r, i && (t.mediaType = i);
|
|
740
|
-
})());
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
r.length > 0 && await Promise.all(r);
|
|
744
|
-
}, Ot = (e) => {
|
|
745
|
-
let t = Array.isArray(e) ? e : [];
|
|
746
|
-
for (let e of t) {
|
|
747
|
-
if (!e || typeof e != "object" || !("role" in e) || e.role !== "user") continue;
|
|
748
|
-
let t = Array.isArray(e.content) ? e.content : null;
|
|
749
|
-
if (t) for (let e = 0; e < t.length; e += 1) {
|
|
750
|
-
let n = t[e];
|
|
751
|
-
if (!n || typeof n != "object" || n.type !== "file") continue;
|
|
752
|
-
let r = X(n.mediaType);
|
|
753
|
-
if (r?.startsWith("image/") || r === "application/pdf") continue;
|
|
754
|
-
let i = X(n.filename) ?? X(n.name) ?? `attachment-${e + 1}`, a = n.data;
|
|
755
|
-
if (r?.startsWith("text/") && a instanceof Uint8Array) {
|
|
756
|
-
let n = (Buffer.isBuffer(a) ? a : Buffer.from(a)).toString("utf8");
|
|
757
|
-
n.length > ut && (n = `${n.slice(0, ut)}\n\n[Truncated]`);
|
|
758
|
-
let o = r === "text/csv" || i.toLowerCase().endsWith(".csv") ? "csv" : "";
|
|
759
|
-
t[e] = {
|
|
760
|
-
type: "text",
|
|
761
|
-
text: `${`Attached file "${i}" (${r}):`}${o ? `\n\n\`\`\`${o}\n${n}\n\`\`\`` : `\n\n\`\`\`\n${n}\n\`\`\``}`
|
|
762
|
-
};
|
|
763
|
-
continue;
|
|
764
|
-
}
|
|
765
|
-
let o = typeof a == "string" && a.trim() ? `\nURL: ${a}` : "";
|
|
766
|
-
t[e] = {
|
|
767
|
-
type: "text",
|
|
768
|
-
text: `Attached file "${i}" (${r ?? "unknown"}) cannot be sent as a file to this OpenAI model (only images and PDFs are supported).${o}`
|
|
769
|
-
};
|
|
770
|
-
}
|
|
771
|
-
}
|
|
772
|
-
}, kt = async (e, t, n) => {
|
|
773
|
-
if (e.message?.role === "user") return it(e.message.parts);
|
|
774
|
-
if (Array.isArray(e.messages)) {
|
|
775
|
-
let t = null;
|
|
776
|
-
for (let n = e.messages.length - 1; n >= 0; --n) {
|
|
777
|
-
let r = e.messages[n];
|
|
778
|
-
if (r?.role !== "user") continue;
|
|
779
|
-
let i = it(r.parts);
|
|
780
|
-
if (i) {
|
|
781
|
-
if (st(i)) return i;
|
|
782
|
-
t ??= i;
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
if (t) return t;
|
|
786
|
-
}
|
|
787
|
-
let r = await m(t, n), i = null;
|
|
788
|
-
for (let e = r.length - 1; e >= 0; --e) {
|
|
789
|
-
let t = r[e];
|
|
790
|
-
if (t.role !== "user") continue;
|
|
791
|
-
let n = it(t.parts);
|
|
792
|
-
if (n) {
|
|
793
|
-
if (st(n)) return n;
|
|
794
|
-
i ??= n;
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
return i ?? "";
|
|
798
|
-
}, At = (e) => {
|
|
799
|
-
let t = Array.isArray(e.messages) && e.messages.length > 0 ? e.messages.at(-1) : e.message;
|
|
800
|
-
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();
|
|
801
|
-
}, jt = (e) => {
|
|
802
|
-
let t = e.id;
|
|
803
|
-
return typeof t == "string" && t.trim() !== "" ? t : null;
|
|
804
|
-
}, Mt = (e) => {
|
|
805
|
-
let t = e.selectedChatModel;
|
|
806
|
-
return typeof t == "string" && t.trim() !== "" ? t : null;
|
|
807
|
-
}, Nt = (e) => {
|
|
808
|
-
let t = e.openaiReasoningEffort;
|
|
809
|
-
return typeof t == "string" && t.trim() !== "" ? t.trim() : null;
|
|
810
|
-
}, Pt = (e) => {
|
|
811
|
-
if (!e || typeof e != "object") return !1;
|
|
812
|
-
let t = e.state, n = e.toolCallId;
|
|
813
|
-
return typeof n == "string" && n.trim() !== "" && (t === "approval-responded" || t === "output-denied");
|
|
814
|
-
}, Ft = (e) => {
|
|
815
|
-
let t = Array.isArray(e.messages) ? e.messages : [];
|
|
816
|
-
return t.length === 0 || t.at(-1)?.role === "user" ? !1 : t.some((e) => (Array.isArray(e?.parts) ? e.parts : []).some((e) => Pt(e)));
|
|
817
|
-
}, It = (e) => {
|
|
818
|
-
let t = /* @__PURE__ */ new Map();
|
|
819
|
-
for (let n of e) {
|
|
820
|
-
let e = Array.isArray(n?.parts) ? n.parts : [];
|
|
821
|
-
for (let n of e) Pt(n) && t.set(n.toolCallId, n);
|
|
822
|
-
}
|
|
823
|
-
return t;
|
|
824
|
-
}, Lt = (e, t) => {
|
|
825
|
-
let n = [];
|
|
826
|
-
return {
|
|
827
|
-
changedMessages: n,
|
|
828
|
-
updatedMessages: e.map((e) => {
|
|
829
|
-
let r = !1, i = e.parts.map((e) => {
|
|
830
|
-
if (!e || typeof e != "object") return e;
|
|
831
|
-
let n = X(e.toolCallId);
|
|
832
|
-
if (!n) return e;
|
|
833
|
-
let i = t.get(n);
|
|
834
|
-
return i ? (r = !0, {
|
|
835
|
-
...e,
|
|
836
|
-
...i
|
|
837
|
-
}) : e;
|
|
838
|
-
});
|
|
839
|
-
if (!r) return e;
|
|
840
|
-
let a = {
|
|
841
|
-
...e,
|
|
842
|
-
parts: i
|
|
843
|
-
};
|
|
844
|
-
return n.push(a), a;
|
|
845
|
-
})
|
|
846
|
-
};
|
|
847
|
-
}, Rt = (e) => {
|
|
848
|
-
if (!e || typeof e != "object" || !("createdAt" in e)) return null;
|
|
849
|
-
let t = e.createdAt;
|
|
850
|
-
if (typeof t != "string") return null;
|
|
851
|
-
let n = new Date(t);
|
|
852
|
-
return Number.isNaN(n.getTime()) ? null : n;
|
|
853
|
-
}, zt = (e) => ({
|
|
854
|
-
latitude: null,
|
|
855
|
-
longitude: null,
|
|
856
|
-
city: null,
|
|
857
|
-
country: null
|
|
858
|
-
}), Bt = (e) => {
|
|
859
|
-
let [t] = e.split("/");
|
|
860
|
-
return t && t !== e ? t : "unknown";
|
|
861
|
-
}, Vt = (e) => {
|
|
862
|
-
switch (Bt(e)) {
|
|
863
|
-
case "openai": return "OpenAI";
|
|
864
|
-
case "google": return "Google Gemini";
|
|
865
|
-
case "xai": return "xAI";
|
|
866
|
-
default: return "Provider";
|
|
867
|
-
}
|
|
868
|
-
}, Ht = (e) => {
|
|
869
|
-
switch (Bt(e)) {
|
|
870
|
-
case "openai": return "Set OPENAI_API_KEY and try again.";
|
|
871
|
-
case "google": return "Set GOOGLE_GENERATIVE_AI_API_KEY or GOOGLE_API_KEY and try again.";
|
|
872
|
-
case "xai": return "Set XAI_API_KEY and try again.";
|
|
873
|
-
default: return "Check the provider API key and try again.";
|
|
874
|
-
}
|
|
875
|
-
}, Ut = (e) => {
|
|
876
|
-
let t = a().chatModels ?? [];
|
|
877
|
-
for (let n of t) {
|
|
878
|
-
if (typeof n == "string") {
|
|
879
|
-
if (n === e) return e;
|
|
880
|
-
continue;
|
|
881
|
-
}
|
|
882
|
-
if (n.id !== e) continue;
|
|
883
|
-
let t = n.name;
|
|
884
|
-
return typeof t == "string" && t.trim() ? t.trim() : n.id;
|
|
885
|
-
}
|
|
886
|
-
let [, n] = e.split("/", 2);
|
|
887
|
-
return n || e;
|
|
888
|
-
}, Wt = (e) => typeof e.type == "string" ? !ht.has(e.type) : !1, Z = (e) => typeof e == "number" && Number.isFinite(e) ? e : void 0, Gt = (e) => e instanceof Error && e.message.trim() ? e.message : "Unknown error", Kt = (e, t) => {
|
|
889
|
-
let n = Gt(e).toLowerCase(), r = Vt(t);
|
|
890
|
-
return n.includes("api key") || n.includes("apikey") || n.includes("unauthorized") || n.includes("invalid authentication") || n.includes("401") ? `${r} API key is missing or invalid. ${Ht(t)}` : n.includes("quota") || n.includes("rate limit") || n.includes("rate_limit") || n.includes("billing") || n.includes("credit") || n.includes("429") ? `${r} could not process this request because of quota, rate limit, or billing limits. Check provider usage and billing, then try again.` : n.includes("tool approval") || n.includes("approvalid") || n.includes("approval id") || n.includes("tool call") || n.includes("tool result") || n.includes("missing tool") ? "The tool approval state for this message is out of date. Please retry the tool call." : n.includes("model not found") || n.includes("not found") || n.includes("unsupported model") || n.includes("404") ? `${r} could not use the selected model "${t}". Check the model configuration and provider access.` : "Something went wrong.";
|
|
891
|
-
}, qt = (e) => e instanceof Error ? {
|
|
892
|
-
errorName: e.name,
|
|
893
|
-
errorMessage: e.message,
|
|
894
|
-
errorStack: e.stack,
|
|
895
|
-
errorCause: e.cause
|
|
896
|
-
} : { errorValue: e }, Q = (e, t, n) => {
|
|
897
|
-
console.error(e, {
|
|
898
|
-
...n,
|
|
899
|
-
...qt(t)
|
|
900
|
-
});
|
|
901
|
-
}, Jt = (e) => ({
|
|
902
|
-
chatId: jt(e),
|
|
903
|
-
selectedChatModel: Mt(e)
|
|
904
|
-
}), Yt = (e) => {
|
|
905
|
-
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 : {};
|
|
906
|
-
return {
|
|
907
|
-
inputTokens: Z(t.inputTokens),
|
|
908
|
-
outputTokens: Z(t.outputTokens),
|
|
909
|
-
totalTokens: Z(t.totalTokens),
|
|
910
|
-
cachedInputTokens: Z(n.cacheReadTokens) ?? Z(t.cachedInputTokens),
|
|
911
|
-
reasoningTokens: Z(r.reasoningTokens) ?? Z(t.reasoningTokens),
|
|
912
|
-
rawUsage: Object.keys(t).length > 0 ? t.raw ?? t : void 0
|
|
913
|
-
};
|
|
914
|
-
}, Xt = () => ({
|
|
915
|
-
inputTokens: 0,
|
|
916
|
-
outputTokens: 0,
|
|
917
|
-
totalTokens: 0,
|
|
918
|
-
cachedInputTokens: 0,
|
|
919
|
-
reasoningTokens: 0
|
|
920
|
-
}), Zt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: r, mode: i }) => {
|
|
921
|
-
try {
|
|
922
|
-
return { workspaceId: X((await a().resolveUsageContext?.({
|
|
923
|
-
ctx: e,
|
|
924
|
-
chatId: t,
|
|
925
|
-
agent: n,
|
|
926
|
-
selectedChatModel: r,
|
|
927
|
-
mode: i
|
|
928
|
-
}))?.workspaceId) ?? void 0 };
|
|
929
|
-
} catch (e) {
|
|
930
|
-
return console.warn("Failed to resolve agent usage context.", e), { workspaceId: void 0 };
|
|
931
|
-
}
|
|
932
|
-
}, Qt = async ({ ctx: e, chatId: t, agent: n, selectedChatModel: r, mode: i }) => {
|
|
933
|
-
let o = a().shouldGenerateChatTitle;
|
|
934
|
-
if (!o) return !0;
|
|
935
|
-
try {
|
|
936
|
-
return await o({
|
|
937
|
-
ctx: e,
|
|
938
|
-
chatId: t,
|
|
939
|
-
agent: n,
|
|
940
|
-
selectedChatModel: r,
|
|
941
|
-
mode: i
|
|
942
|
-
});
|
|
943
|
-
} catch (e) {
|
|
944
|
-
return console.warn("Failed to resolve chat title generation setting.", e), !0;
|
|
945
|
-
}
|
|
946
|
-
}, $ = async ({ ctx: e, usageContext: t, agent: n, chatId: r, mode: i, feature: a, modelId: o, status: s, billable: c, usage: l, finishReason: u, error: d, startedAt: f, finishedAt: p = /* @__PURE__ */ new Date() }) => {
|
|
947
|
-
let m = l ? Yt(l) : {}, h = {
|
|
948
|
-
id: A(),
|
|
949
|
-
workspaceId: t.workspaceId,
|
|
950
|
-
agentId: n.id,
|
|
951
|
-
chatId: r,
|
|
952
|
-
mode: i,
|
|
953
|
-
feature: a,
|
|
954
|
-
provider: Bt(o),
|
|
955
|
-
model: o,
|
|
956
|
-
billable: c,
|
|
957
|
-
status: s,
|
|
958
|
-
finishReason: X(u) ?? void 0,
|
|
959
|
-
errorMessage: d ? Gt(d) : void 0,
|
|
960
|
-
...m,
|
|
961
|
-
startedAt: f,
|
|
962
|
-
finishedAt: p,
|
|
963
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
964
|
-
};
|
|
965
|
-
try {
|
|
966
|
-
await v(e, h);
|
|
967
|
-
} catch (e) {
|
|
968
|
-
console.error("Failed to save agents usage event.", e);
|
|
969
|
-
}
|
|
970
|
-
}, $t = (e) => `agents-sdk:chat:${e}:stream`, en = async ({ ctx: e, chatId: t, selectedChatModel: n }) => await a().resolveAgent?.({
|
|
971
|
-
ctx: e,
|
|
972
|
-
chatId: t,
|
|
973
|
-
selectedChatModel: n
|
|
974
|
-
}) ?? i(), tn = ({ ctx: e, chatId: t, mode: n, streamTransport: r }) => {
|
|
975
|
-
let i = o(e), a = $t(t), s = S({
|
|
976
|
-
chatId: t,
|
|
977
|
-
abortWhenNoSubscribersMs: n === "headless" || r ? 0 : void 0
|
|
978
|
-
});
|
|
979
|
-
n === "interactive" && s.subscribe(e);
|
|
980
|
-
let c = (e) => {
|
|
981
|
-
r && r.publish({
|
|
982
|
-
tenantId: i.tenantId,
|
|
983
|
-
userId: i.userId,
|
|
984
|
-
channel: a,
|
|
985
|
-
payload: e
|
|
986
|
-
});
|
|
987
|
-
};
|
|
988
|
-
return {
|
|
989
|
-
abortController: s.abortController,
|
|
990
|
-
publishJson: (e) => {
|
|
991
|
-
s.publishJson(e), c({
|
|
992
|
-
chatId: t,
|
|
993
|
-
part: e
|
|
994
|
-
});
|
|
995
|
-
},
|
|
996
|
-
publishDone: () => {
|
|
997
|
-
s.publishDone(), c({
|
|
998
|
-
chatId: t,
|
|
999
|
-
done: !0
|
|
1000
|
-
});
|
|
1001
|
-
}
|
|
1002
|
-
};
|
|
1003
|
-
}, nn = ({ ctx: e, chatId: t, streamTransport: n, message: r }) => {
|
|
1004
|
-
if (!n) return;
|
|
1005
|
-
let i = o(e);
|
|
1006
|
-
n.publish({
|
|
1007
|
-
tenantId: i.tenantId,
|
|
1008
|
-
userId: i.userId,
|
|
1009
|
-
channel: $t(t),
|
|
1010
|
-
payload: {
|
|
1011
|
-
chatId: t,
|
|
1012
|
-
message: r
|
|
1013
|
-
}
|
|
1014
|
-
});
|
|
1015
|
-
}, rn = async ({ payload: e, ctx: i, mode: c = "interactive", streamTransport: d = null }) => {
|
|
1016
|
-
let p = jt(e);
|
|
1017
|
-
if (!p) return r(i, "bad_request:api", "Parameter id is required.");
|
|
1018
|
-
let g = e, _ = Mt(g), v = vt(process.env.PLAYWRIGHT), x = !vt(process.env.AGENT_SDK_LIVE_CHAT) && v || process.env.NODE_ENV === "test";
|
|
1019
|
-
if (!_) return r(i, "bad_request:api", "Parameter selectedChatModel is required.");
|
|
1020
|
-
if (_ === ft && (x = !0), _ !== ft && (!yt().has(_) || !me(_))) return r(i, "bad_request:api", `Unsupported selectedChatModel: "${_}".`);
|
|
1021
|
-
let S = process.env.OPENAI_API_KEY, C = process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY, w = process.env.XAI_API_KEY, T = ue(_), E = de(_), D = fe(_), O = Nt(g), k = O && O !== "default" && O !== "off" ? O : null, ae = n(_);
|
|
1022
|
-
if (k && !ae.some((e) => e === k)) return r(i, "bad_request:api", `Unsupported reasoning effort "${k}" for selectedChatModel: "${_}".`);
|
|
1023
|
-
if (!x && T && !S) return r(i, "bad_request:provider", "Missing OPENAI_API_KEY.");
|
|
1024
|
-
if (!x && E && !C) return r(i, "bad_request:provider", "Missing GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY).");
|
|
1025
|
-
if (!x && D && !w) return r(i, "bad_request:provider", "Missing XAI_API_KEY.");
|
|
1026
|
-
if (!x && !T && !E && !D) return r(i, "bad_request:provider", `Unsupported selectedChatModel: "${_}".`);
|
|
1027
|
-
let j = await en({
|
|
1028
|
-
ctx: i,
|
|
1029
|
-
chatId: p,
|
|
1030
|
-
selectedChatModel: _
|
|
1031
|
-
}), oe = await a().resolveKnowledge?.({
|
|
1032
|
-
ctx: i,
|
|
1033
|
-
chatId: p,
|
|
1034
|
-
agent: j,
|
|
1035
|
-
selectedChatModel: _
|
|
1036
|
-
}) ?? null, M = await Zt({
|
|
1037
|
-
ctx: i,
|
|
1038
|
-
chatId: p,
|
|
1039
|
-
agent: j,
|
|
1040
|
-
selectedChatModel: _,
|
|
1041
|
-
mode: c
|
|
1042
|
-
}), N = await Qt({
|
|
1043
|
-
ctx: i,
|
|
1044
|
-
chatId: p,
|
|
1045
|
-
agent: j,
|
|
1046
|
-
selectedChatModel: _,
|
|
1047
|
-
mode: c
|
|
1048
|
-
}), se = o(i), P = await l(i, p, { includeDeleted: !0 });
|
|
1049
|
-
if (P?.deletedAt) return r(i, "not_found:chat");
|
|
1050
|
-
P ? P.selectedChatModel !== _ && await u(i, {
|
|
1051
|
-
chatId: p,
|
|
1052
|
-
selectedChatModel: _
|
|
1053
|
-
}) : await h(i, {
|
|
1054
|
-
id: p,
|
|
1055
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
1056
|
-
userId: se.userId,
|
|
1057
|
-
title: "",
|
|
1058
|
-
isStreaming: !1,
|
|
1059
|
-
selectedChatModel: _,
|
|
1060
|
-
lastContext: null
|
|
1061
|
-
});
|
|
1062
|
-
let F = g.message, ce = typeof F?.id == "string" ? F.id : A(), le = Array.isArray(F?.parts) ? F?.parts : [];
|
|
1063
|
-
if ((typeof F?.role == "string" ? F.role : null) === "user") {
|
|
1064
|
-
let e = /* @__PURE__ */ new Date();
|
|
1065
|
-
await f(i, [{
|
|
1066
|
-
id: ce,
|
|
1067
|
-
chatId: p,
|
|
1068
|
-
role: "user",
|
|
1069
|
-
parts: le,
|
|
1070
|
-
attachments: [],
|
|
1071
|
-
createdAt: e
|
|
1072
|
-
}]), nn({
|
|
1073
|
-
ctx: i,
|
|
1074
|
-
chatId: p,
|
|
1075
|
-
streamTransport: d,
|
|
1076
|
-
message: {
|
|
1077
|
-
id: ce,
|
|
1078
|
-
role: "user",
|
|
1079
|
-
parts: le,
|
|
1080
|
-
metadata: { createdAt: e.toISOString() }
|
|
1081
|
-
}
|
|
1082
|
-
});
|
|
1083
|
-
}
|
|
1084
|
-
if (x) {
|
|
1085
|
-
await y(i, {
|
|
1086
|
-
chatId: p,
|
|
1087
|
-
isStreaming: !0
|
|
1088
|
-
});
|
|
1089
|
-
let e = tn({
|
|
1090
|
-
ctx: i,
|
|
1091
|
-
chatId: p,
|
|
1092
|
-
mode: c,
|
|
1093
|
-
streamTransport: d
|
|
1094
|
-
});
|
|
1095
|
-
try {
|
|
1096
|
-
if (N) {
|
|
1097
|
-
let t = st(await kt(g, i, p)), n = await l(i, p);
|
|
1098
|
-
n && rt(n.title) && t && t !== n.title && (await s(i, {
|
|
1099
|
-
chatId: p,
|
|
1100
|
-
title: t
|
|
1101
|
-
}), e.publishJson({
|
|
1102
|
-
type: "data-chat-title",
|
|
1103
|
-
data: t,
|
|
1104
|
-
transient: !0
|
|
1105
|
-
}));
|
|
1106
|
-
}
|
|
1107
|
-
let t = A();
|
|
1108
|
-
v && !e.abortController.signal.aborted && await gt(600), e.publishJson({
|
|
1109
|
-
type: "start",
|
|
1110
|
-
messageId: t
|
|
1111
|
-
});
|
|
1112
|
-
let n = "text-1";
|
|
1113
|
-
e.publishJson({
|
|
1114
|
-
type: "text-start",
|
|
1115
|
-
id: n
|
|
1116
|
-
});
|
|
1117
|
-
let r = At(g), a = r ? `Echo: ${r}` : "Hello from agents-sdk", o = Date.now(), u = a.split(/(\s+)/).filter((e) => e.length > 0);
|
|
1118
|
-
for (let t of u) {
|
|
1119
|
-
if (e.abortController.signal.aborted) break;
|
|
1120
|
-
e.publishJson({
|
|
1121
|
-
type: "text-delta",
|
|
1122
|
-
id: n,
|
|
1123
|
-
delta: t
|
|
1124
|
-
}), await gt(v ? 120 : 80);
|
|
1125
|
-
}
|
|
1126
|
-
if (v && !e.abortController.signal.aborted) {
|
|
1127
|
-
let e = Date.now() - o, t = 1200;
|
|
1128
|
-
e < t && await gt(t - e);
|
|
1129
|
-
}
|
|
1130
|
-
return e.abortController.signal.aborted ? {} : (e.publishJson({
|
|
1131
|
-
type: "text-end",
|
|
1132
|
-
id: n
|
|
1133
|
-
}), e.publishJson({
|
|
1134
|
-
type: "finish",
|
|
1135
|
-
finishReason: "stop"
|
|
1136
|
-
}), e.publishDone(), await f(i, [{
|
|
1137
|
-
id: t,
|
|
1138
|
-
chatId: p,
|
|
1139
|
-
role: "assistant",
|
|
1140
|
-
parts: [{
|
|
1141
|
-
type: "text",
|
|
1142
|
-
text: a
|
|
1143
|
-
}],
|
|
1144
|
-
attachments: [],
|
|
1145
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
1146
|
-
}]), await $({
|
|
1147
|
-
ctx: i,
|
|
1148
|
-
usageContext: M,
|
|
1149
|
-
agent: j,
|
|
1150
|
-
chatId: p,
|
|
1151
|
-
mode: c,
|
|
1152
|
-
feature: "chat",
|
|
1153
|
-
modelId: _,
|
|
1154
|
-
status: "success",
|
|
1155
|
-
billable: !1,
|
|
1156
|
-
usage: Xt(),
|
|
1157
|
-
finishReason: "stop",
|
|
1158
|
-
startedAt: new Date(o)
|
|
1159
|
-
}), {});
|
|
1160
|
-
} finally {
|
|
1161
|
-
await _t(i, p);
|
|
1162
|
-
}
|
|
1163
|
-
}
|
|
1164
|
-
let I = zt(i), L = Ft(g);
|
|
1165
|
-
if (Array.isArray(g.messages) && !L) {
|
|
1166
|
-
let e = g.messages.flatMap((e) => {
|
|
1167
|
-
let t = typeof e?.id == "string" ? e.id : null, n = typeof e?.role == "string" ? e.role : null, r = Array.isArray(e?.parts) ? e.parts : [];
|
|
1168
|
-
return !t || !n ? [] : [{
|
|
1169
|
-
id: t,
|
|
1170
|
-
chatId: p,
|
|
1171
|
-
role: n,
|
|
1172
|
-
parts: r,
|
|
1173
|
-
attachments: [],
|
|
1174
|
-
createdAt: Rt(e?.metadata) ?? /* @__PURE__ */ new Date()
|
|
1175
|
-
}];
|
|
1176
|
-
});
|
|
1177
|
-
e.length > 0 && await f(i, e);
|
|
1178
|
-
}
|
|
1179
|
-
let R;
|
|
1180
|
-
if (Array.isArray(g.messages) && g.messages.length > 0 && L) {
|
|
1181
|
-
let e = await m(i, p);
|
|
1182
|
-
if (e.length === 0) R = g.messages;
|
|
1183
|
-
else {
|
|
1184
|
-
let { changedMessages: t, updatedMessages: n } = Lt(e, It(g.messages));
|
|
1185
|
-
t.length > 0 && await f(i, t), R = n.map((e) => ({
|
|
1186
|
-
id: e.id,
|
|
1187
|
-
role: e.role,
|
|
1188
|
-
parts: e.parts,
|
|
1189
|
-
metadata: { createdAt: e.createdAt.toISOString() }
|
|
1190
|
-
}));
|
|
1191
|
-
}
|
|
1192
|
-
} else R = Array.isArray(g.messages) && g.messages.length > 0 ? g.messages : (await m(i, p)).map((e) => ({
|
|
1193
|
-
id: e.id,
|
|
1194
|
-
role: e.role,
|
|
1195
|
-
parts: e.parts,
|
|
1196
|
-
metadata: { createdAt: e.createdAt.toISOString() }
|
|
1197
|
-
}));
|
|
1198
|
-
let z = L ? {
|
|
1199
|
-
messages: R,
|
|
1200
|
-
lastContext: P?.lastContext ?? null,
|
|
1201
|
-
lastContextChanged: !1
|
|
1202
|
-
} : await He({
|
|
1203
|
-
ctx: i,
|
|
1204
|
-
chatId: p,
|
|
1205
|
-
agent: j,
|
|
1206
|
-
selectedChatModel: _,
|
|
1207
|
-
mode: c,
|
|
1208
|
-
messages: R,
|
|
1209
|
-
lastContext: P?.lastContext ?? null
|
|
1210
|
-
});
|
|
1211
|
-
if (!L && z.lastContextChanged) try {
|
|
1212
|
-
await b(i, {
|
|
1213
|
-
chatId: p,
|
|
1214
|
-
lastContext: z.lastContext
|
|
1215
|
-
});
|
|
1216
|
-
} catch (e) {
|
|
1217
|
-
console.warn("Failed to save compacted agent chat history context.", e);
|
|
1218
|
-
}
|
|
1219
|
-
let B = z.messages;
|
|
1220
|
-
await y(i, {
|
|
1221
|
-
chatId: p,
|
|
1222
|
-
isStreaming: !0
|
|
1223
|
-
});
|
|
1224
|
-
let V = tn({
|
|
1225
|
-
ctx: i,
|
|
1226
|
-
chatId: p,
|
|
1227
|
-
mode: c,
|
|
1228
|
-
streamTransport: d
|
|
1229
|
-
}), H = "", U = "";
|
|
1230
|
-
if (N) try {
|
|
1231
|
-
H = await kt(g, i, p), U = st(H);
|
|
1232
|
-
let e = await l(i, p);
|
|
1233
|
-
e && rt(e.title) && U && U !== e.title && (await s(i, {
|
|
1234
|
-
chatId: p,
|
|
1235
|
-
title: U
|
|
1236
|
-
}), V.publishJson({
|
|
1237
|
-
type: "data-chat-title",
|
|
1238
|
-
data: U,
|
|
1239
|
-
transient: !0
|
|
1240
|
-
}));
|
|
1241
|
-
} catch (e) {
|
|
1242
|
-
Q("Failed to prepare agent chat title.", e, {
|
|
1243
|
-
chatId: p,
|
|
1244
|
-
selectedChatModel: _,
|
|
1245
|
-
agentId: j.id,
|
|
1246
|
-
mode: c
|
|
1247
|
-
}), V.publishJson({
|
|
1248
|
-
type: "error",
|
|
1249
|
-
errorText: "Something went wrong."
|
|
1250
|
-
}), V.publishDone();
|
|
1251
|
-
try {
|
|
1252
|
-
await _t(i, p);
|
|
1253
|
-
} catch (e) {
|
|
1254
|
-
Q("Failed to update chat streaming state.", e, {
|
|
1255
|
-
chatId: p,
|
|
1256
|
-
selectedChatModel: _,
|
|
1257
|
-
agentId: j.id,
|
|
1258
|
-
mode: c
|
|
1259
|
-
});
|
|
1260
|
-
}
|
|
1261
|
-
return {};
|
|
1262
|
-
}
|
|
1263
|
-
N && H && U && S && (async () => {
|
|
1264
|
-
let e = /* @__PURE__ */ new Date();
|
|
1265
|
-
try {
|
|
1266
|
-
let { text: t } = await ne({
|
|
1267
|
-
model: ge(),
|
|
1268
|
-
system: xe,
|
|
1269
|
-
prompt: H,
|
|
1270
|
-
onFinish: async (t) => {
|
|
1271
|
-
await $({
|
|
1272
|
-
ctx: i,
|
|
1273
|
-
usageContext: M,
|
|
1274
|
-
agent: j,
|
|
1275
|
-
chatId: p,
|
|
1276
|
-
mode: c,
|
|
1277
|
-
feature: "title",
|
|
1278
|
-
modelId: pt,
|
|
1279
|
-
status: "success",
|
|
1280
|
-
billable: !0,
|
|
1281
|
-
usage: t.totalUsage ?? t.usage,
|
|
1282
|
-
finishReason: t.finishReason,
|
|
1283
|
-
startedAt: e
|
|
1284
|
-
});
|
|
1285
|
-
}
|
|
1286
|
-
}), n = at(t);
|
|
1287
|
-
if (!n) return;
|
|
1288
|
-
let r = await l(i, p);
|
|
1289
|
-
if (!r) return;
|
|
1290
|
-
r.title !== n && (await s(i, {
|
|
1291
|
-
chatId: p,
|
|
1292
|
-
title: n
|
|
1293
|
-
}), V.publishJson({
|
|
1294
|
-
type: "data-chat-title",
|
|
1295
|
-
data: n,
|
|
1296
|
-
transient: !0
|
|
1297
|
-
}));
|
|
1298
|
-
} catch (t) {
|
|
1299
|
-
await $({
|
|
1300
|
-
ctx: i,
|
|
1301
|
-
usageContext: M,
|
|
1302
|
-
agent: j,
|
|
1303
|
-
chatId: p,
|
|
1304
|
-
mode: c,
|
|
1305
|
-
feature: "title",
|
|
1306
|
-
modelId: pt,
|
|
1307
|
-
status: "error",
|
|
1308
|
-
billable: !1,
|
|
1309
|
-
error: t,
|
|
1310
|
-
startedAt: e
|
|
1311
|
-
}), console.warn("Failed to generate chat title.", t);
|
|
1312
|
-
}
|
|
1313
|
-
})();
|
|
1314
|
-
let ve = te({
|
|
1315
|
-
originalMessages: R,
|
|
1316
|
-
onError: (e) => (Q("Agent chat stream failed.", e, {
|
|
1317
|
-
chatId: p,
|
|
1318
|
-
selectedChatModel: _,
|
|
1319
|
-
agentId: j.id,
|
|
1320
|
-
mode: c
|
|
1321
|
-
}), Kt(e, _)),
|
|
1322
|
-
onFinish: async ({ responseMessage: e }) => {
|
|
1323
|
-
let t = Array.isArray(e.parts) ? e.parts : [];
|
|
1324
|
-
await f(i, [{
|
|
1325
|
-
id: e.id ?? A(),
|
|
1326
|
-
chatId: p,
|
|
1327
|
-
role: e.role ?? "assistant",
|
|
1328
|
-
parts: t,
|
|
1329
|
-
attachments: [],
|
|
1330
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
1331
|
-
}]);
|
|
1332
|
-
},
|
|
1333
|
-
execute: async ({ writer: e }) => {
|
|
1334
|
-
let t = Xe({
|
|
1335
|
-
ctx: i,
|
|
1336
|
-
dataStream: e,
|
|
1337
|
-
requestHints: I
|
|
1338
|
-
}), n = [
|
|
1339
|
-
"getWeather",
|
|
1340
|
-
"createDocument",
|
|
1341
|
-
"editDocument",
|
|
1342
|
-
"updateDocument",
|
|
1343
|
-
"requestSuggestions",
|
|
1344
|
-
"webSearch"
|
|
1345
|
-
], r = [
|
|
1346
|
-
"getWeather",
|
|
1347
|
-
"createDocument",
|
|
1348
|
-
"editDocument",
|
|
1349
|
-
"updateDocument",
|
|
1350
|
-
"requestSuggestions"
|
|
1351
|
-
], o = pe(_), s = o ? [] : T ? n : r, l = t, u = s, d = await a().resolveTools?.({
|
|
1352
|
-
ctx: i,
|
|
1353
|
-
dataStream: e,
|
|
1354
|
-
requestHints: I,
|
|
1355
|
-
agent: j,
|
|
1356
|
-
selectedChatModel: _,
|
|
1357
|
-
availableTools: t,
|
|
1358
|
-
defaultActiveTools: s
|
|
1359
|
-
});
|
|
1360
|
-
d && (l = d.tools, u = d.activeTools ?? Object.keys(d.tools)), u = nt({
|
|
1361
|
-
activeTools: u,
|
|
1362
|
-
availableTools: l,
|
|
1363
|
-
userText: At(g)
|
|
1364
|
-
});
|
|
1365
|
-
let f = await ee(B.map((e) => ({
|
|
1366
|
-
role: e?.role,
|
|
1367
|
-
parts: e?.parts,
|
|
1368
|
-
metadata: e?.metadata
|
|
1369
|
-
})), {
|
|
1370
|
-
tools: l,
|
|
1371
|
-
ignoreIncompleteToolCalls: !0
|
|
1372
|
-
});
|
|
1373
|
-
await Dt(i, f), T && Ot(f);
|
|
1374
|
-
let m = typeof g.openaiReasoningSummary == "string" ? g.openaiReasoningSummary : null, h;
|
|
1375
|
-
T && k ? h = { openai: {
|
|
1376
|
-
reasoningEffort: k,
|
|
1377
|
-
reasoningSummary: m ?? void 0
|
|
1378
|
-
} } : D && o && k && (h = { xai: { reasoningEffort: k } });
|
|
1379
|
-
let v = !1, y = /* @__PURE__ */ new Date(), b = async ({ status: e, usage: t, finishReason: n, error: r }) => {
|
|
1380
|
-
v || (v = !0, await $({
|
|
1381
|
-
ctx: i,
|
|
1382
|
-
usageContext: M,
|
|
1383
|
-
agent: j,
|
|
1384
|
-
chatId: p,
|
|
1385
|
-
mode: c,
|
|
1386
|
-
feature: "chat",
|
|
1387
|
-
modelId: _,
|
|
1388
|
-
status: e,
|
|
1389
|
-
billable: e === "success",
|
|
1390
|
-
usage: t,
|
|
1391
|
-
finishReason: n,
|
|
1392
|
-
error: r,
|
|
1393
|
-
startedAt: y
|
|
1394
|
-
}));
|
|
1395
|
-
}, x = Ut(_), S = !1, C, te = () => {
|
|
1396
|
-
C &&= (clearTimeout(C), void 0);
|
|
1397
|
-
}, w = (t, n) => {
|
|
1398
|
-
S && t !== "thinking" || e.write({
|
|
1399
|
-
type: "data-waiting-status",
|
|
1400
|
-
data: {
|
|
1401
|
-
phase: t,
|
|
1402
|
-
message: n,
|
|
1403
|
-
modelId: _,
|
|
1404
|
-
modelName: x
|
|
1405
|
-
},
|
|
1406
|
-
transient: !0
|
|
1407
|
-
});
|
|
1408
|
-
}, ne = () => {
|
|
1409
|
-
S || (S = !0, te(), w("thinking", "Thinking..."));
|
|
1410
|
-
}, E = () => {
|
|
1411
|
-
S = !0, te();
|
|
1412
|
-
};
|
|
1413
|
-
w("waiting", "Waiting..."), C = setTimeout(() => {
|
|
1414
|
-
w("still-waiting", "Still waiting...");
|
|
1415
|
-
}, mt);
|
|
1416
|
-
let O = (() => {
|
|
1417
|
-
try {
|
|
1418
|
-
return ie({
|
|
1419
|
-
model: he(_),
|
|
1420
|
-
system: _e({
|
|
1421
|
-
selectedChatModel: _,
|
|
1422
|
-
requestHints: I,
|
|
1423
|
-
agentInstructions: j.instructions,
|
|
1424
|
-
knowledge: oe
|
|
1425
|
-
}),
|
|
1426
|
-
messages: f,
|
|
1427
|
-
tools: l,
|
|
1428
|
-
stopWhen: re(5),
|
|
1429
|
-
abortSignal: V.abortController.signal,
|
|
1430
|
-
providerOptions: h,
|
|
1431
|
-
activeTools: u,
|
|
1432
|
-
onFinish: async (e) => {
|
|
1433
|
-
E(), await b({
|
|
1434
|
-
status: "success",
|
|
1435
|
-
usage: e.totalUsage ?? e.usage,
|
|
1436
|
-
finishReason: e.finishReason
|
|
1437
|
-
});
|
|
1438
|
-
},
|
|
1439
|
-
onError: async (e) => {
|
|
1440
|
-
E();
|
|
1441
|
-
let t = e?.error ?? e;
|
|
1442
|
-
Q("Agent model stream failed.", t, {
|
|
1443
|
-
chatId: p,
|
|
1444
|
-
selectedChatModel: _,
|
|
1445
|
-
agentId: j.id,
|
|
1446
|
-
mode: c
|
|
1447
|
-
}), await b({
|
|
1448
|
-
status: "error",
|
|
1449
|
-
error: t
|
|
1450
|
-
});
|
|
1451
|
-
},
|
|
1452
|
-
onAbort: async (e) => {
|
|
1453
|
-
E(), await b({
|
|
1454
|
-
status: "aborted",
|
|
1455
|
-
usage: e?.totalUsage ?? e?.usage,
|
|
1456
|
-
finishReason: e?.finishReason
|
|
1457
|
-
});
|
|
1458
|
-
},
|
|
1459
|
-
onChunk: ({ chunk: e }) => {
|
|
1460
|
-
Wt(e) && ne();
|
|
1461
|
-
}
|
|
1462
|
-
});
|
|
1463
|
-
} catch (e) {
|
|
1464
|
-
throw E(), e;
|
|
1465
|
-
}
|
|
1466
|
-
})();
|
|
1467
|
-
e.merge(O.toUIMessageStream({
|
|
1468
|
-
originalMessages: R,
|
|
1469
|
-
onError: (e) => Kt(e, _),
|
|
1470
|
-
sendReasoning: o || !!(T && k)
|
|
1471
|
-
}));
|
|
1472
|
-
}
|
|
1473
|
-
});
|
|
1474
|
-
return (async () => {
|
|
1475
|
-
let e = null, n = null, r = Date.now(), a = !1, o = null, s = async () => {
|
|
1476
|
-
let e = Date.now();
|
|
1477
|
-
if (!(e - r < 6e4)) {
|
|
1478
|
-
r = e;
|
|
1479
|
-
try {
|
|
1480
|
-
await y(i, {
|
|
1481
|
-
chatId: p,
|
|
1482
|
-
isStreaming: !0
|
|
1483
|
-
});
|
|
1484
|
-
} catch (e) {
|
|
1485
|
-
console.warn("Failed to refresh chat streaming heartbeat.", e);
|
|
1486
|
-
}
|
|
1487
|
-
}
|
|
1488
|
-
}, l = () => {
|
|
1489
|
-
if (!a || o) return;
|
|
1490
|
-
let e = s().finally(() => {
|
|
1491
|
-
o === e && (o = null);
|
|
1492
|
-
});
|
|
1493
|
-
o = e;
|
|
1494
|
-
}, u = () => {
|
|
1495
|
-
a = !0;
|
|
1496
|
-
let e = setInterval(() => {
|
|
1497
|
-
l();
|
|
1498
|
-
}, t);
|
|
1499
|
-
return async () => {
|
|
1500
|
-
a = !1, clearInterval(e), await o;
|
|
1501
|
-
};
|
|
1502
|
-
};
|
|
1503
|
-
try {
|
|
1504
|
-
let t = ve.getReader();
|
|
1505
|
-
for (e = () => t.releaseLock(), n = u();;) {
|
|
1506
|
-
let { value: e, done: n } = await t.read();
|
|
1507
|
-
if (n) break;
|
|
1508
|
-
V.publishJson(e), await s();
|
|
1509
|
-
}
|
|
1510
|
-
V.publishDone();
|
|
1511
|
-
} catch (e) {
|
|
1512
|
-
Q("Agent chat runtime stream failed.", e, {
|
|
1513
|
-
chatId: p,
|
|
1514
|
-
selectedChatModel: _,
|
|
1515
|
-
agentId: j.id,
|
|
1516
|
-
mode: c
|
|
1517
|
-
}), V.publishJson({
|
|
1518
|
-
type: "error",
|
|
1519
|
-
errorText: Kt(e, _)
|
|
1520
|
-
}), V.publishDone();
|
|
1521
|
-
} finally {
|
|
1522
|
-
await n?.(), e?.();
|
|
1523
|
-
try {
|
|
1524
|
-
await _t(i, p);
|
|
1525
|
-
} catch (e) {
|
|
1526
|
-
Q("Failed to update chat streaming state.", e, {
|
|
1527
|
-
chatId: p,
|
|
1528
|
-
selectedChatModel: _,
|
|
1529
|
-
agentId: j.id,
|
|
1530
|
-
mode: c
|
|
1531
|
-
});
|
|
1532
|
-
}
|
|
1533
|
-
}
|
|
1534
|
-
})(), {};
|
|
1535
|
-
}, an = async (e, t) => {
|
|
1536
|
-
try {
|
|
1537
|
-
return await rn({
|
|
1538
|
-
payload: e,
|
|
1539
|
-
ctx: t,
|
|
1540
|
-
mode: "interactive"
|
|
1541
|
-
});
|
|
1542
|
-
} catch (n) {
|
|
1543
|
-
return Q("Agent chat request failed.", n, {
|
|
1544
|
-
...Jt(e),
|
|
1545
|
-
mode: "interactive"
|
|
1546
|
-
}), r(t, "internal:api");
|
|
1547
|
-
}
|
|
1548
|
-
}, on = async (e, t) => {
|
|
1549
|
-
let n = t.req.query.id, i = Array.isArray(n) ? n[0] : n;
|
|
1550
|
-
return typeof i != "string" || i.trim() === "" ? r(t, "bad_request:api") : g(t, i);
|
|
1551
|
-
}, sn = (t) => {
|
|
1552
|
-
t.get(ct, (async (t, n) => {
|
|
1553
|
-
let i = n.req.query.id, a = Array.isArray(i) ? i[0] : i;
|
|
1554
|
-
if (typeof a != "string" || a.trim() === "") return r(n, "bad_request:api", "Parameter id is required.");
|
|
1555
|
-
let o = await l(n, a);
|
|
1556
|
-
if (!o) return r(n, "not_found:chat");
|
|
1557
|
-
let s = x(a);
|
|
1558
|
-
return e(o) && (!s || s.isDone) && (o = await d(n, o)), o;
|
|
1559
|
-
})), t.post(ct, an), t.delete(ct, on);
|
|
1560
|
-
};
|
|
1561
|
-
//#endregion
|
|
1562
|
-
export { sn as default, rn as runAgentLoop };
|