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